from Utility import *
from Config import *
from Process import *
# from ChangeLog import *
import sys
import urllib3
import Utility
# import ChangeLog
# Directory = "C:\\DBMigrations\\RCCP\\";


ToRenameMigrationFile = []

# BuildEnv
# 1 - Staging
# 2 - Production
def ProcessParam(ModuleId, Platform, BuildEnv, JobName=None, IsLocalCompileNum=None):
    # print("haha");
    CurrentModule = GetCurrentModule(ModuleId, BuildEnv);    
    print(CurrentModule)
    # global BuildEnvironment
    Utility.BuildEnvironment = BuildEnv
    # print(Platform)
    try:
        Platform = int(Platform);
        if CurrentModule and (0 <= Platform <= 2):
            IsDirectoryExist = CheckDirectoryExist(CurrentModule["ProjectLocalPath"])
            if(IsDirectoryExist):
                IsLocalCompile = False;
                if IsLocalCompileNum:
                    try: 
                        if(int(IsLocalCompileNum) == 1):
                            # print("islocalcompile")
                            IsLocalCompile = True;
                    except:
                        print("exception as");
                # print(IsLocalCompile)
                StartProcess(CurrentModule, Platform, BuildEnv, JobName, IsLocalCompile)
                # print("StartProcess")
            else:
                EndProgram("Directory Not Exist End Program")
        else:
            if CurrentModule:
                print("Platform greater than 2")
            else:
                print("Module Id not found")
    except:
        print("Platform not integer.")

def GetDBMigrations(ModuleId, ZIPFileName, BuildEnv):
    ModuleKey = "";
    Directory = DBMigrationsDir;
    if(ModuleId == "7643207E-1E9A-428D-AE31-E4C573ED5BDA"):
        ModuleKey = "RCCP";
    elif(ModuleId == "2A88944E-0E25-412D-B2D6-94522EF8DAE2"):
        ModuleKey = "RCM";
    BuildEnvString = "Production" if BuildEnv == 2 else "Staging"
    if(ModuleKey):
        Directory = DBMigrationsDir + BuildEnvString + "\\" + ModuleKey + "\\";
    
    FileList = DirectoryFile(Directory);
    # print(FileList)
    ToCheckMigrationFileList = [];
    for file in FileList:
        if "Migration_" + ModuleKey in file:
            ToCheckMigrationFileList.append(file)
    # print(ToCheckMigrationFileList);
    
    MigrationHistory = "";
    for file in ToCheckMigrationFileList:
        Migration = GetCodeFirstMigration(Directory + file);
        if Migration:
            MigrationHistory += "\n--" + file + Migration;
    # print(MigrationHistory);
    if MigrationHistory:
        WriteToFile(Directory + "ProcessMigrations\\"+ ZIPFileName +".txt", MigrationHistory);
    
    for file in ToRenameMigrationFile:
        Dir = os.path.dirname(file) + "\\";
        FileName = os.path.basename(file);
        NewFileName = "";
        try:
            NewFileName = FileName.split('_')[0] + "_PD_" + FileName.split('_')[1] + "_" + FileName.split('_')[2] + "_" + FileName.split('_')[3];            
        except:
            print("err");
        if NewFileName:
            RenameFile(Dir, FileName, NewFileName);
    return MigrationHistory;

def GetCodeFirstMigration(Path):
    result = "";
    # Path = "C:\\RCCP\\Migration_RCCP_20200713_1115.txt";
    # Path = "C:\\RCCP\\Migration_RCCP_20200713_1223.txt";
    
    if CheckFileExist(Path):
        FileContent = ReadFileContent(Path);
        MigrationString = "[dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion]";
        MigrationExists = CheckContentExist(FileContent, MigrationString);
        if MigrationExists:
            result = GetMigrationsContent(FileContent);
        # RenameFile();
        ToRenameMigrationFile.append(Path);
    return result;

def GetMigrationsContent(FileContent):
    words = FileContent.split("\n")
    BeforeString = "";
    AfterString = "";
    for index, value in enumerate(words):
        if "Applying automatic migration:" in value:
            BeforeString = value;
        
        if "[dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])" in value:
            AfterString = value;

    Migration = FileContent.split(BeforeString, 1)[1];
    Migration = Migration.split(AfterString,1)[0];
    return str(Migration);

def StartProcess(CurrentModule, Platform, BuildEnv, JobName, IsLocalCompile):
    print("Start Process");
    try:
        ModuleGUIDList = [];
        ModuleGUIDList.append(CurrentModule["ModuleId"]);
        print(ModuleGUIDList)
        GetRCMDetailsURL = CentralServerUrl() + "api/action/GetRetailCamModuleForUpdateArchiveTool"

        Response = CallApi(GetRCMDetailsURL, "POST", headers={
            'Content-Type': 'application/json'
        }, payload=json.dumps(ModuleGUIDList))
        print(Response.text)

        if(Response.status_code == 200):
            parseRCMDetails = json.loads(Response.text)
            for i in parseRCMDetails:
                if i["ModuleId"] == CurrentModule["ModuleId"]:
                    ZIPFilePath = ZIPProcess(CurrentModule, i, Platform)
                    # ZIPFilePath = "D:\\Project\\FFC-RCCP\\RetailCamControlPanel\\Updater\\RetailCamControlPanel\\UpdateZIP_RetailCamControlPanel_1_20200826_033528.ZIP";
                    print(ZIPFilePath)
                    if(ZIPFilePath != ""):    
                        ZIPFileName = os.path.basename(ZIPFilePath)
                        Revision = ZIPFileName.split('_')[2]

                        SQLChanges = None
                        StoreProcScript = None
                        if(i["IsCodeFirst"]):
                            # Get DB Migration
                            print("Code First, Get Migration.")
                            SQLChanges = GetDBMigrations(CurrentModule["ModuleId"], ZIPFileName, BuildEnv)
                            if(CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA"):
                                SQLChanges += "\n" + GetToSyncTableDBScript()
                            StoreProcScript = GetSPScript(CurrentModule["ModuleId"], Revision)
                            print("SQL Changes")
                            print(SQLChanges)
                            print("SP")
                            print(StoreProcScript)
                        else:
                            # Direct Pack the required File
                            print("not code first")
                            if(CurrentModule["ModuleId"] == GetModuleId("SupportPortal") or CurrentModule["ModuleId"] == GetModuleId("PartnerPortal")):
                                print("Get DB Changes")
                                SQLChanges = GetDatabaseScript(CurrentModule["ModuleId"], Revision);
                                print("SQL Changes")
                                print(SQLChanges)
                        # Get Changelog
                        ChangeLog = None;#GetChangeLog(JobName)
                        print(ChangeLog)
                        if not IsLocalCompile:
                            print("Uploading to Central Server.")
                            UploadFileToCentralServer(ZIPFilePath, i, Platform, SQLChanges, StoreProcScript, ChangeLog)
                            print("Update Archive Successfully upload to Central Server.")
                        else:
                            print("Local Compile Completed.")
                else:
                    print("not selected module")
    except Exception as e:
        print("StartProcess exception")
        print(str(e))
               
def ZIPProcess(CurrentModule, ModuleDetails, Platform):
    print("ZIPProcess")
    # Get CUrrent Module Version
    result = "";
    GetModuleVersionUrl = CentralServerUrl() + "api/action/GetModuleLatestRevision?ModuleId=" + ModuleDetails["ModuleId"] + "&Platform=" + str(Platform)
    Response = None
    if(CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA"):
        GetModuleVersionUrl = CentralServerRCCPUrl() + "api/action/GetRCCPDBRevision"
        Response = CallApi(GetModuleVersionUrl, "GET")
    else:
        Response = CallApi(GetModuleVersionUrl, "POST")
    print(Response.text)
    if(Response.status_code == 200):
        ModuleVersions = None
        if(CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA"):
            ModuleVersions = int(Response.text.replace("\"", "")) + 1 if Response.text != "" else 1;
        else:
            ModuleVersions = int(Response.text) + 1 if Response.text != "" else 1
        
        IncludeFoldersAndFiles = []
        if(CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA"):
            UpdateArchiveName = GetZipFileName(ModuleDetails["ModuleName"], ModuleVersions, Platform, True)
        else:
            UpdateArchiveName = GetZipFileName(ModuleDetails["ModuleName"], ModuleVersions, Platform, False)
        UpdateArchiveModulePath = "Updater\\" + ModuleDetails["ModuleName"] + "\\"

        if(Platform == 0):
            # Cross Platform
            IncludeFoldersAndFiles = ModuleDetails["CommonIncludeFoldersAndFiles"];            
        elif(Platform == 1):
            # Window Platform
            IncludeFoldersAndFiles = ModuleDetails["WindowsIncludeFoldersAndFiles"]
            UpdateArchiveModulePath += "Windows\\"
        elif(Platform == 2):
            # Linux Platform
            IncludeFoldersAndFiles = ModuleDetails["LinuxIncludeFoldersAndFiles"]
            UpdateArchiveModulePath += "Linux\\"

        UpdateArchiveModuleWorkingPath = CurrentModule["ProjectLocalPath"] + UpdateArchiveModulePath + "Working\\" + str(ModuleVersions) + "\\"
        IncludeFoldersAndFiles = json.loads(IncludeFoldersAndFiles);        
        
        #Copy Dir
        CopyDirSuccess = CopyDirAndSubDir(IncludeFoldersAndFiles["IncludeFolders"], CurrentModule["ProjectLocalPath"], UpdateArchiveModuleWorkingPath)

        #Copy File
        CopyFileSuccess = False;
        if CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA": #RCCP Follow File Structure
            CopyFileSuccess = CopyFile(IncludeFoldersAndFiles["IncludeFiles"], CurrentModule["ProjectLocalPath"], UpdateArchiveModuleWorkingPath, True);
        else:
            CopyFileSuccess = CopyFile(IncludeFoldersAndFiles["IncludeFiles"], CurrentModule["ProjectLocalPath"], UpdateArchiveModuleWorkingPath, False);

        if(CopyDirSuccess and CopyFileSuccess):
            ZIPFilePath = CurrentModule["ProjectLocalPath"] + UpdateArchiveModulePath + UpdateArchiveName + ".ZIP";
            SplitList = UpdateArchiveName.split('_');
            ZIPPassword = SplitList[3] + "_" + SplitList[4];
            if CurrentModule["ModuleId"] == "7643207E-1E9A-428D-AE31-E4C573ED5BDA":
                print(UpdateArchiveModuleWorkingPath);
                WriteToFile(UpdateArchiveModuleWorkingPath + "version", str(ModuleVersions));
                WriteToFile(UpdateArchiveModuleWorkingPath + "." + UpdateArchiveName + ".txt", "Update_Archive Date: " + ZIPPassword);
            
            ZIPSuccess = ZipFileWith7ZA(UpdateArchiveModuleWorkingPath, ZIPFilePath, ZIPPassword);
            if ZIPSuccess:
                CleanDirectoryPath = UpdateArchiveModuleWorkingPath.replace(str(ModuleVersions) + "\\", "");
                IsCleanSuccess = DeleteDir(CleanDirectoryPath);
                if IsCleanSuccess:
                    print("Finish Cleaning Working Directory.");
                else:
                    print("Failed to Clean Working Directory.");


            ZIPFileExists = CheckFileExist(ZIPFilePath);
            if(ZIPFileExists):
                # do something
                result = ZIPFilePath;
    return result;

def GetSPScript(ModuleId, LatestRevision):
    GetSPScriptURL = CentralServerUrl() + "api/action/GetStoreProcScript?ModuleId=" + ModuleId + "&Revision=" + LatestRevision;
    SPScriptString = "";
    SPScript = "";
    APIResponse = CallApi(GetSPScriptURL, "GET");
    if APIResponse.status_code == 200:
        SPScriptString = APIResponse.text;
        SPScriptList = json.loads(SPScriptString);
        # print(SPScriptList);
        for i in SPScriptList:
            SPScript += i + "\n\n";
    # print(SPScript)
    return SPScript;

def GetDatabaseScript(ModuleId, LatestRevision):
    GetDBScriptURL = CentralServerUrl() + "api/action/GetDBScript?ModuleId=" + ModuleId + "&Revision=" + LatestRevision;
    DBScriptString = "";
    DBScript = "";
    APIResponse = CallApi(GetDBScriptURL, "GET");
    if APIResponse.status_code == 200:
        DBScriptString = APIResponse.text;
        DBScriptList = json.loads(DBScriptString);
        # print(DBScriptList);
        for i in DBScriptList:
            DBScript += i + "\n\n";
    # print(DBScript)
    return DBScript;


def UploadFileToCentralServer(ZIPFilePath, Module, Platform, SQLChanges, StoreProcScript, Changelog):
    try:
        ZIPFileName = os.path.basename(ZIPFilePath);
        Revision = ZIPFileName.split('_')[2];
        FileMD5 = MD5Generator(ZIPFilePath);
        # print(Module);
        UploadFileObj = {};
        UploadFileObj["ModuleId"] = Module["ModuleId"];
        UploadFileObj["ModuleName"] = Module["ModuleName"];
        UploadFileObj["FileName"] = ZIPFileName;
        UploadFileObj["MD5"] = FileMD5;
        UploadFileObj["CurrentRevision"] = Revision;
        if SQLChanges or StoreProcScript:
            UploadFileObj["HasDbChanges"] = True;
        else:
            UploadFileObj["HasDbChanges"] = False;
        UploadFileObj["SQLChanges"] = SQLChanges;
        UploadFileObj["StoreProcScript"] = StoreProcScript;
        UploadFileObj["ChangeLog"] = Changelog;
        UploadFileObj["IsReleased"] = True;
        UploadFileObj["Platform"] = Platform;
        UploadFileObj["Type"] = Module["Type"];
        UploadFileObj["Username"] = "Jenkins";
        UploadFileObj["SyncToClientServer"] = Module["SyncToClientServer"];
        
        UploadAPI = Module["ApiToUploadPackage"];
        # UploadAPI = UploadAPI.replace("https://portal.footfallcam.com/", "http://localhost:53582/");
        
        # url = "http://localhost:11111/api/action/UploadZIPFile"

        payload = {'ZIPDetails': json.dumps(UploadFileObj)}
        files = [
        # ('', open("D:\\as1232d.txt",'rb'))
            ('', open(ZIPFilePath,'rb'))
        ]
        headers= {}
        
        print(UploadAPI, headers, files, payload)
        response = requests.request("POST", UploadAPI, headers=headers, data = payload, files = files)
        # print(UploadFileObj);
        print(response.text)
        
    except Exception as e:
        print("Exception in UploadFileToCentralServer");
        print(str(e));

def GetToSyncTableDBScript():
    URL = CentralServerUrl() + "api/action/GetToSyncTableDBScript"
    DBScriptFilePath = []
    APIResponse = CallApi(URL, "GET")
    if APIResponse.status_code == 200:
        DBScriptFilePath = APIResponse.text

    try:
        file = requests.get(DBScriptFilePath)
        DBScript = file.text.encode('utf-8')
    except Exception as e:
        print("Read ToSyncTableDBScript error")
        print(str(e))
   
    return DBScript

def EndProgram(Message):
    print(Message);


# GetDirectoryFile();
# print(GetCodeFirstMigration());
# FileList = DirectoryFile("C:\\RCCP\\");
# RenameFile(Directory, "Migration_RCCP_20200803_154813_test.txt", "Migration_RCCP_20200803_154813.txt")
# print(FileList)

# StartProcess("7643207E-1E9A-428D-AE31-E4C573ED5BDA", 0);
# PassObj = {
#     "ModuleId": "2A88944E-0E25-412D-B2D6-94522EF8DAE2",
#     "ProjectLocalPath": "D:\\Project\\RetailCamModules\\RetailCamModules\\"
#   };
# PassObj = {
#     "ModuleId": "7643207E-1E9A-428D-AE31-E4C573ED5BDA",
#     "ProjectLocalPath": "D:\\Project\\FFC-RCCP\\RetailCamControlPanel\\"
#   };
# PassObj = {
#     "ModuleId": "69B78B85-64FF-4B12-B53D-9F754A6DCC29",
#     "ProjectLocalPath": "D:\\Project\\RetailCamModules\\RCM_WInSvc\\"
#   };
# PassObj = {
#     "ModuleId": "4F536062-7087-474B-AEB3-15872AF0858C",
#     "ProjectLocalPath": "D:\\Project\\DataManagerAPI\\DataManagerAPI\\"
#   };
# StartProcess(PassObj, 0);
# UploadFileToCentralServer("ss");
# GetDirectoryFile(PassObj["ModuleId"], "test");
