import os
import requests
import json
import random
import string
import time
import math
from datetime import datetime
from pathlib import Path
import os
from distutils.dir_util import copy_tree
from shutil import copyfile
import shutil
# from zipfile import ZipFilepython
from os.path import basename
# import py7zr
import hashlib
# import zipfile
import subprocess
import pathlib
import sys

# CentralServerUrl = "https://central.footfallcam.com/";
# SevenZIPAPath = "C:\RetailCamUpdater\7za.exe";
JenkinsUrl = "http://192.168.2.71:8080/jenkins/";
JenkinsToken = "ZGVwbG95bWVudDoxMWVjNmI3NTlmNWZlMzNiM2ZjN2Y3NzViOTdhYjU0MGEz";
JenkinsUsername = 'deployment'
JenkinsPassword = '$z-!p.LUenR?2Hgt'

def RootDir():
    ROOT_DIR = pathlib.Path(__file__).parent
    return ROOT_DIR

SevenZIPAPath = str(RootDir()) + "\\7za.exe";
DBMigrationsDir = str(RootDir()) + "\\DBMigrations\\";
global BuildEnvironment

def CentralServerUrl():
    if(BuildEnvironment == 0):
        print("Utlity Global BuildEnv not set")
    CentralServerUrl = "https://staging-central.footfallcam.com:8880/" if BuildEnvironment == 1 else "https://central.footfallcam.com/"
    return CentralServerUrl

def CentralServerRCCPUrl():
    return "http://192.168.2.76:8873/" if BuildEnvironment == 1 else "https://v9.footfallcam.com/"


def ReadJson(jsonString=None, filename=None):
    if filename is not None and filename != "":
        with open(filename) as f_in:
            return json.load(f_in)
    elif jsonString is not None and jsonString != "":
        return json.loads(jsonString)
    else:
        return None


def CallApi(url, method, headers=None, payload=None):
    h = {"Content-Type": "application/json"}
    response = requests.request(method, url, headers=h, data=payload)
    return response


def TimestampUtcNow():
    return math.floor(time.time())


def ConvertToDateTime(timestampValue):
    return datetime.utcfromtimestamp(timestampValue).strftime('%Y-%m-%d %H:%M:%S')


def get_random_string(length):
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(length))
    return result_str


def split_dataframe(df, chunk_size=10000):
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i * chunk_size: (i + 1) * chunk_size])
    return chunks

def CheckDirectoryExist(Path):
    # haha = Path.exists();
    IsDirExist = os.path.isdir(Path);
    # print(IsDirExist);
    return IsDirExist

def CheckFileExist(Path):
        # haha = Path.exists();
    IsFileExist = os.path.exists(Path);
    # print(IsDirExist);
    return IsFileExist;

def DeleteDir(Path):
    result = False;
    try:
        shutil.rmtree(Path);
        result = True;
    except Exception as e:
        print("Delete Directory Error.");
        print("To Delete Directory = " + Path);
        print(str(e));
    return result;


def RenameFile(Directory, OldFileName, NewFileName):    
    try:
        if(os.path.exists(Directory + OldFileName)):
            os.rename(Directory + OldFileName, Directory + NewFileName) 
    except:
        print("Rename " + OldFileName + " error");

def DirectoryFile(Directory):
    FileList = [];
    for file in os.listdir(Directory):
        FileList.append(file);
    return FileList;

def ReadFileContent(FilePath):
    content = "";
    if(os.path.exists(FilePath)):
        with open(FilePath, 'r') as content_file:
            content = content_file.read();
    return content;

def CheckContentExist(Content, SearchContent):
    if SearchContent in Content:
        return True;
    else:
        return False;

def GetZipFileName(ModuleName, ModuleVersion, Platform, IsRCCP):
    result = "";
    ConvertTime = datetime.utcnow().strftime('%Y%m%d_%H%M%S');
    if IsRCCP:
        result = "Update_Archive_" + str(ModuleVersion) + "_" + ConvertTime;
    else:
        if(Platform == 0):
            result = "UpdateZIP_" + ModuleName + "_" + str(ModuleVersion) + "_" + ConvertTime;
        else:
            result = "UpdateZIP_" + ModuleName + "_" + str(ModuleVersion) + "_" + ConvertTime + "_" + GetPlatformName(Platform);
    return result;

def GetPlatformName(Platform):
    result = "";
    if(Platform == 1):
        result = "Windows";
    elif(Platform == 2):
        result = "Linux";
    return result;

def CopyDirAndSubDir(DirectoryToCopy, CopyFrom, CopyTo):
    IsSuccess = False;
    print("IM IN COPYDIR AND SUBDIR:")
    print(DirectoryToCopy)
    try:
        
        for dir in DirectoryToCopy:
            fromDirectory = CopyFrom + dir;
            toDirectory = CopyTo + dir;

            print("fromDirectory: ")
            print(fromDirectory)

            print("toDirectory: ")
            print(toDirectory)

            copy_tree(fromDirectory, toDirectory)
        IsSuccess = True;
    except:
        print("Error occur on CopyDirAndSubDir.");
    
    print(IsSuccess)
    return IsSuccess;

def CopyFile(FileToCopy, CopyFrom, CopyTo, FollowDirStuc):
    IsSuccess = False;
    print("FileToCopy")
    print(FileToCopy)
    try:
        for file in FileToCopy:


            fromPath = CopyFrom + file;
            print("Frompath: ")
            print(fromPath)
            print("\n")

            print("CopyTo: ")
            print(CopyTo)
            print("\n")
            if not os.path.exists(CopyTo):
                os.makedirs(CopyTo)

            if not os.path.basename(fromPath):
                # is directory copy all file in directory
                copy_tree(fromPath, CopyTo)
            else:
                # not directory
                toPath = CopyTo + file;
                print("toPath")
                print(toPath)
                if FollowDirStuc:
                    Path = os.path.dirname(toPath)
                    if not os.path.exists(Path):
                        os.makedirs(Path)
                    copyfile(fromPath, toPath);
                else:
                    toPath = CopyTo + os.path.basename(fromPath);
                    copyfile(fromPath, toPath);
        IsSuccess = True;
    except Exception as e:
        print("Error occur on CopyFile");
        print(str(e));
    return IsSuccess;

# def SevenZIP(ToZIPDir, OutputFile, Password=False, FollowDirStructure=True):
#     # with py7zr.SevenZipFile(OutputFile, 'w', password=Password) as archive:
#     #     archive.writeall(ToZIPDir)    
#     result = False;
#     try:        
#         archive = py7zr.SevenZipFile(OutputFile, 'w', password=Password)
#         # archive.write(ToZIPDir);
#         for folderName, subfolders, filenames in os.walk(ToZIPDir):
#             for filename in filenames:
#                 #create complete filepath of file in directory
#                 filePath = os.path.join(folderName, filename);
#                 # Add file to zip
#                 if FollowDirStructure:
#                     fileDir = filePath.replace(ToZIPDir, "");
#                     archive.write(filePath, fileDir);
#                 else:
#                     archive.write(filePath, basename(filePath));
#         if Password:
#             archive.password = Password;
#         archive.close();
#         result = True;
#     except:
#         print("7zip Exception.");
#     return result;

def ZipFileWith7ZA(ToZIPDir, OutputFile, Password=False):
    result = False;
    try:
        Command = "";
        if os.path.exists(SevenZIPAPath):
            if Password:
                Command = "\"" + SevenZIPAPath + "\" a -p" + Password + " \"" + OutputFile + "\" * -x!7za.exe > NUL"
            else:
                Command = "\"" + SevenZIPAPath + "\" a \"" + OutputFile + " \"* -x!7za.exe > NUL"
            print(Command)
            # result = subprocess.check_output(Command, shell=True)
            proc = subprocess.Popen(Command, cwd=ToZIPDir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            tmp = proc.stdout.read()
            # print(tmp);
            if os.path.exists(OutputFile):
                result = True;
        else:
            print("7za not found.");
    except:
        print("7zip Exception.");
    return result;

def MD5Generator(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def WriteToFile(Path, Content):    
    try:
        if not os.path.exists(os.path.dirname(Path)):
            os.makedirs(os.path.dirname(Path))
        textfile = open(Path, 'w')
        textfile.write(Content)
        textfile.close()
    except:
        print("Write to file error.");

def GetModuleId(ModuleName):
    ModuleName = ModuleName.lower();
    ModuleId = "";
    if(ModuleName == "supportportal"):
        ModuleId = "578DE12D-9EAB-4ADC-9194-310FF68497B5"
    elif(ModuleName == "partnerportal"):
        ModuleId = "5B585DF8-F669-4D7D-A224-72DCB37D80E9"
    elif(ModuleName == "CentralServerControl"):
        ModuleId = ""
    elif(ModuleName == "retailcamcontrolpanel"):
        ModuleId = "7643207E-1E9A-428D-AE31-E4C573ED5BDA"
    elif(ModuleName == "retailcammodule"):
        ModuleId = "2A88944E-0E25-412D-B2D6-94522EF8DAE2"
    return ModuleId;

