#!/usr/bin/env python
# encoding: utf-8

"""
@version: 
@author: Will
@license: 
@contact: 
@site: http://www.timesnotes.com
@file: sock_client.py
@time: 15-12-17 下午4:24
"""

import socket
import os
import sys
import json
import hashlib

class MyFtpClient(object):

    def __init__(self,host,port):
        self.host = host
        self.port = port
        self.sock = socket.socket()
        self.sock.connect((self.host,self.port))

    def updata(self,fileName):
        # 上传数据
        # 先上传以文件信息组成的list，["fileup",filename,filesize]，使用json序列化后传递
        # sock = socket.socket()
        # sock.connect((self.host,self.port))
        # sock.settimeout(60)
        file_lst = ["fileup",]  # ["fileup",filename,filesize]
        file_lst.append(fileName)
        file_lst.append(os.path.getsize(fileName))
        str_file_lst = json.dumps(file_lst)
        fileMD5 = hashlib.md5()
        self.sock.sendall(str_file_lst)
        if self.sock.recv(100) == "exist":
            print "file name is already exist"
        else:
            with open(fileName,"rb") as fr:
                while 1:
                    tmp_file_content = fr.read(1024)
                    if not tmp_file_content:
                        break
                    fileMD5.update(tmp_file_content)
                    self.sock.sendall(tmp_file_content)
            tmp_data = self.sock.recv(100)
            self.sock.sendall(fileMD5)
            tmp_data = self.sock.recv(100)
            print tmp_data



    def downdata(self,filename):
        # 下载数据
        fileMD5 =hashlib.md5()
        if os.path.exists(filename):
            return "Fils is already exists."

        # self.sock = socket.socket()
        # sock.connect((self.host,self.port))
        self.sock.sendall(["fileget",filename])
        file_info = json.loads(self.sock.recv(100))
        fileSize = file_info[1]

        with open(filename,"wb") as fw:
            while 1:
                if fileSize<=0:
                    break
                data = self.sock.recv(1024)
                fileMD5.update(data)
                fw.write(data)
                fileSize = fileSize-1024

        server_fileMD5 = self.sock.recv(100)
        if server_fileMD5 == fileMD5:
            print "file data is not lost"
        else:
            print "file data is lost"


    def loginFtp(self):
        username = raw_input("Input usrname :")
        if username == "quit":
            return 2
        password = raw_input("Input password:")

        # sock = socket.socket()
        # sock.connect((self.host,self.port))
        atmp = json.dumps(["login",username,password])
        print atmp,type(atmp) ##############
        self.sock.sendall(atmp)
        data = self.sock.recv(100)

        print data,"data is"        ###############
        # data = self.sock.recv(100)
        if data =="right":
            print "Right"
            self.sock.close()
            return 1
        elif data == "wrong":
            print "Wrong"
            return 0

    def getcmd(self,cmd):
        # sock = socket.socket()
        # sock.connect((self.host,self.port))
        print cmd
        tmpLst = ["cmd",cmd]
        str_tmpList = json.dumps(tmpLst)
        print tmpLst,str_tmpList,type(str_tmpList)
        self.sock.sendall(str_tmpList)
        data = ""
        contSize = json.loads( self.sock.recv(100) )
        self.sock.sendall("receive length")
        while 1:
            if contSize<=0:
                break
            data = self.sock.recv(1024)
            contSize -= 1024
            print data,

    def getWelcome(self):
        # sk = socket.socket()
        # sk.connect((self.host,self.port))
        data = self.sock.recv(1024)
        print data

    def closeConn(self):
        self.sock.close()


if __name__=="__main__":
    fc = MyFtpClient("127.0.0.1",8021)
    fc.getWelcome()
    flag = True
    while flag:
        print "Need login"
        while 1:
            login = fc.loginFtp()
            if login == 0:
                print "Wrong username or password"
                continue
            elif login == 2:
                fc.closeConn()
                sys.exit()
            elif login == 1:
                flag = False
                break
    while 1:
        userinp = raw_input("Operation:")
        if userinp.strip()== "quit":
            fc.closeConn()
            break

        elif userinp.strip().startswith("get"):
            fc.updata(userinp.strip().split()[1])

        elif userinp.strip().startswith("up"):
            fc.downdata(userinp.strip().split()[1])
        else:
            fc.getcmd(userinp)



















