define(["angular","lodash","cjt/util/locale","uiBootstrap","app/services/versionControlService","app/services/sseAPIService","cjt/services/alertService","cjt/directives/alert","cjt/directives/alertList","cjt/directives/actionButtonDirective","jquery-chosen","angular-chosen","cjt/decorators/angularChosenDecorator"],(function(e,t,o){"use strict";var a=e.module("cpanel.versionControl");return a.value("PAGE",PAGE),a.controller("ManageRepositoriesController",["$scope","$window","$location","$timeout","versionControlService","sseAPIService","PAGE","$routeParams","alertService","sshKeyVerification","$q",function(e,a,s,n,r,l,i,p,c,d,u){var m=this;m.isRTL=!1;var y=document.querySelector("html");y&&(m.isRTL="rtl"===y.getAttribute("dir")),m.isLoading=!0,m.deployInProgress=!1,m.deployState="",m.deployedTaskInformation=null,m.deployCalloutType="info";var h,g="",f=["log_update","task_complete","task_failed"],v={json:!0},k=["basic-info","deploy"],b=0,_=decodeURIComponent(p.repoPath);function T(e){return r.getRepositoryInformation(e,"available_branches").then((function(e){m.branchList=e&&e.available_branches||[]}),(function(e){return m.unableToRetrieveAvailableBranches=!0,u.reject(e)}))}function C(){return T(m.repoPath).catch((function(){c.add({type:"danger",id:"retrieve-branches-again-error",message:t.escape(o.maketext("The system cannot update information for the repository at “[_1]” because it cannot access the remote repository.",m.repoPath)),closeable:!0,replace:!0,group:"versionControl"})}))}function D(e){return e.then((function(e){return m.ssh.status=e,C()}),(function(e){c.add({type:"danger",message:t.escape(o.maketext("The system failed to add the fingerprints from “[_1]” to the [asis,known_hosts] file: [_2]",m.ssh.hostname,e)),closeable:!0,replace:!0,group:"versionControl",id:"known-hosts-verification-failure"})})).finally((function(){m.ssh.modal.close(),delete m.ssh.modal}))}function R(e){m.name=e.name,m.repoPath=e.repository_root,m.cloneURL=e.clone_urls.read_write[0],m.branch=e.branch,m.checkedoutBranch=e.branch,m.hasActiveBranch=e.hasActiveBranch,m.hasHeadInformation=e.hasHeadInformation,m.lastUpdateSHA=e.lastUpdateSHA,m.lastUpdateDate=e.lastUpdateDate,m.commitMessage=e.commitMessage,m.author=e.author,e.available_branches&&(m.branchList=e.available_branches),m.hasRemote=e.hasRemote,m.remoteInformation=e.source_repository,m.gitWebURL=e.gitWebURL,m.fileManagerRedirectURL=e.fileManagerRedirectURL,m.fullRepoPath=m.repoPath,m.qaSafeSuffix=e.qaSafeSuffix,m.deployInProgress=e.deployInProgress,m.deployable=e.deployable,m.hasDeploymentInformation=e.hasDeploymentInformation,m.lastDeployedDate=e.lastDeployedDate,m.lastDeployedSHA=e.lastDeployedSHA,m.lastDeployedAuthor=e.lastDeployedAuthor,m.lastDeployedCommitDate=e.lastDeployedCommitDate,m.lastDeployedCommitMessage=e.lastDeployedCommitMessage,m.changesAvailableToDeploy=e.lastDeployedSHA!==e.lastUpdateSHA,m.deployTasks=A(e.tasks),void 0===h&&m.deployInProgress&&x()}function A(e){var a=t.map(e,(function(e){if("deploy"===e.action){var t=function(e){var t;if(e){t=e.split("/").pop().match(/\d+(\.\d+)/g)}return t[0]}(e.args.log_file);return{task_id:e.task_id,log_file:e.args.log_file,sse_url:e.sse_url,timeStamp:t,humanReadableDate:o.local_datetime(t,"datetime_format_medium")}}}));return t.sortBy(a,[function(e){return e.log_file}])}function I(){m.deployState="",m.deployCalloutType="info",m.deployedTaskInformation=null,h=null}function x(){var e;m.queuedDeployTasksCount=m.deployTasks.length-1,m.queuedDeployTasksCount&&(m.queuedTaskString=(e=m.queuedDeployTasksCount,o.maketext("[quant,_1,additional task,additional tasks] queued",e))),m.firstDeployTask=m.deployTasks[0],g=m.firstDeployTask.sse_url,m.deployProgress=o.maketext("The deployment that you triggered on [_1] is in progress …",m.firstDeployTask.humanReadableDate),m.deployComplete=o.maketext("The deployment that you triggered on [_1] is complete. Updating last deployment information …",m.firstDeployTask.humanReadableDate),m.deployQueued=o.maketext("The deployment that you triggered on [_1] is queued …",m.firstDeployTask.humanReadableDate),l.initialize()}!function(t){t&&-1!==(b=k.indexOf(t))?e.activeTabIndex=b:s.path("/list/")}(decodeURIComponent(p.tabname)),function(e){var o;r.getRepositoryInformation(e,"name,tasks,clone_urls,branch,last_update,source_repository,last_deployment,deployable").then((function(t){o=t;var a=T(e);return a.catch((function(){var e=d.getHostnameAndPort(t&&t.source_repository&&t.source_repository.url);e&&(m.ssh={},m.ssh.hostname=e.hostname,m.ssh.port=e.port,m.ssh.promise=d.verify(e.hostname,e.port))})),a}),(function(e){c.add({type:"danger",message:t.escape(e),closeable:!0,replace:!1,group:"versionControl"}),s.path("/list/")})).finally((function(){R(o),m.isLoading=!1}))}(_),e.changeActiveTab=function(t){var o=s.url().split("/").pop().toLowerCase();t&&(e.activeTabIndex=k.indexOf(t),o!==t&&s.path("/manage/"+encodeURIComponent(_)+"/"+t))},e.$watch("repository.hasRemote",(function(e){e?(m._noConnectionText=o.maketext("The system could not contact the remote repository."),m._tryAgainTooltipText=o.maketext("Attempt to contact the remote repository again.")):(m._noConnectionText=o.maketext("The system could not read from the repository."),m._tryAgainTooltipText=o.maketext("Attempt to read from the repository again."))})),m.tryAgain=function(){return c.removeById("retrieve-branches-again-error","versionControl"),m.ssh.promise?m.ssh.promise.then((function(){return C()}),(function(e){m.ssh.status=e.status,m.ssh.keys=e.keys,c.clear(null,"versionControl"),m.ssh.modal=d.openModal({hostname:m.ssh.hostname,port:m.ssh.port,type:m.ssh.status,keys:m.ssh.keys,onAccept:D}),m.ssh.modal.result.catch((function(){c.add({type:"danger",message:t.escape(o.maketext("The system [output,strong,cannot] connect to the remote repository if you do not accept the host key for “[output,strong,_1].”",m.ssh.hostname)),closeable:!0,replace:!0,group:"versionControl",id:"known-hosts-verification-cancelled"})})),m.ssh.modal})):C()},m.updateRepository=function(){var e=m.branch===m.checkedoutBranch?"":m.branch;return r.updateRepository(m.repoPath,m.name,e).then((function(e){c.add({type:"success",message:t.escape(o.maketext("The system successfully updated the “[_1]” repository.",m.name)),closeable:!0,replace:!0,autoClose:1e4,group:"versionControl"}),R(e.data)}),(function(e){c.add({type:"danger",message:t.escape(e),closeable:!0,replace:!1,group:"versionControl"})}))},m.pullFromRemote=function(){return r.updateFromRemote(m.repoPath,m.branch).then((function(e){var a=e.data;m.lastUpdateSHA===a.lastUpdateSHA?c.add({type:"info",message:t.escape(o.maketext("The “[_1]” repository is up-to-date.",m.name)),closeable:!0,replace:!0,autoClose:1e4,group:"versionControl"}):(c.add({type:"success",message:t.escape(o.maketext("The system successfully updated the “[_1]” repository.",m.name)),closeable:!0,replace:!0,autoClose:1e4,group:"versionControl"}),m.hasHeadInformation=a.hasHeadInformation,m.lastUpdateSHA=a.lastUpdateSHA,m.lastUpdateDate=a.lastUpdateDate,m.commitMessage=a.commitMessage,m.author=a.author,m.newCommits=!0,n((function(){m.newCommits=!1}),1e4))}),(function(e){c.add({type:"danger",message:t.escape(e),closeable:!0,replace:!1,group:"versionControl"})}))},e.$on("sse:ready",(function(e){g=i.securityToken+g,h=l.connect(g,f,v)})),e.$on("$destroy",(function(){h&&l.close(h)})),e.$on("sse:log_update",(function(t,o){m.deployState="processing",e.$apply()})),e.$on("sse:task_complete",(function(o,a){l.close(h),m.deployCalloutType="success",m.deployState="complete",e.$apply(),n((function(){return r.getRepositoryInformation(m.repoPath,"last_deployment,tasks").then((function(e){m.lastDeployedDate=e.lastDeployedDate,m.lastDeployedSHA=e.lastDeployedSHA,m.lastDeployedAuthor=e.lastDeployedAuthor,m.lastDeployedCommitDate=e.lastDeployedCommitDate,m.lastDeployedCommitMessage=e.lastDeployedCommitMessage,m.hasDeploymentInformation=!0,m.changesAvailableToDeploy=e.lastDeployedSHA!==m.lastUpdateSHA,m.deployTasks=A(e.tasks),I(),m.deployTasks&&m.deployTasks.length>0?(m.deployInProgress=!0,x()):m.deployInProgress=!1,m.newDeployCommit=!0,n((function(){m.newDeployCommit=!1}),5e3)}),(function(e){c.add({type:"danger",message:t.escape(e.message),closeable:!0,replace:!1,group:"versionControl"})}))}),5e3)})),e.$on("sse:task_failed",(function(a,s){l.close(h);var n=function(e){var t={};if(e){var o=e.split("/").pop(),a=i.homeDir+"/.cpanel/logs",s=i.deprefix+"filemanager/showfile.html?file="+encodeURIComponent(o)+"&dir="+encodeURIComponent(a);t.fileName=o,t.fileManagerURL=s}return t}(m.deployedTaskInformation.log_path);return c.add({type:"danger",message:o.maketext("Error occurred while deploying.")+" "+o.maketext("You can view the log file: [output,url,_1,_2,target,_3]",n.fileManagerURL,n.fileName,"_blank"),closeable:!0,replace:!1,group:"versionControl"}),e.$apply(),r.getRepositoryInformation(m.repoPath,"tasks").then((function(e){m.deployTasks=A(e.tasks),I(),m.deployTasks&&m.deployTasks.length>0?(m.deployInProgress=!0,x()):m.deployInProgress=!1}),(function(e){c.add({type:"danger",message:t.escape(e.message),closeable:!0,replace:!1,group:"versionControl"})}))})),m.deployRepository=function(){return r.deployRepository(m.repoPath).then((function(e){var t=e.data||{};m.deployTasks=A([{action:"deploy",task_id:t.task_id,sse_url:t.sse_url,args:{log_file:t.log_path}}]),m.deployTasks&&m.deployTasks.length>0?(m.deployInProgress=!0,x()):m.deployInProgress=!1}),(function(e){m.deployInProgress=!1,c.add({type:"danger",message:t.escape(e)+" "+o.maketext("For more information, read our [output,url,_1,documentation,target,_2].","https://go.cpanel.net/GitDeployment","_blank"),closeable:!0,replace:!1,group:"versionControl"})}))},m.backToListView=function(){s.path("/list")},m.redirectToGitWeb=function(e,t){e?a.open(e,t+"GitWeb"):c.add({type:"danger",message:o.maketext("The system could not find the repository’s [asis,Gitweb] [output,acronym,URL,Universal Resource Locator]."),closeable:!0,replace:!1,group:"versionControl"})},m.redirectToFileManager=function(e,t){e?a.open(e,t+"FileManager"):c.add({type:"danger",message:o.maketext("The system could not redirect you to the File Manager interface."),closeable:!0,replace:!1,group:"versionControl"})},m.cloneToClipboard=function(e){try{r.cloneToClipboard(e)&&c.add({type:"success",message:o.maketext("The system successfully copied the “[_1]” clone [output,acronym,URL,Uniform Resource Locator] to the clipboard.",e),closeable:!0,replace:!1,autoClose:1e4,group:"versionControl"})}catch(e){c.add({type:"danger",message:t.escape(e),closeable:!0,replace:!1,group:"versionControl"})}},m.hasAvailableBranches=function(){return Boolean(m.branchList&&0!==m.branchList.length)}}])}));