/*
 * Copyright 2015,  Sven Stork
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global $, window, location, CSInterface, SystemPath, themeManager, document, app */


// create ILM app
var ILMApp = angular.module("ILMApp", [])

// create ILM controller
ILMApp.controller("ILMAppController", function ($scope, $q) {
    $scope.TAB_ID = Object.freeze({
        // this struct need to be in sync with the definition in hostscript.jsx
        LUMINOSITY_MASKS : 0,
        SATURATION_MASKS : 1,
        SUPPORT          : 2
    })
    $scope.TOOL_ID = Object.freeze({
        TOOL_MENU      : 0,
        TOOL_HIGH      : 1,
        TOOL_MID   : 2,
        TOOL_LOW       : 3,
        TOOL_ZONE      : 4,
        TOOL_FULL      : 5
    })
    $scope.TABS = [
        {
            name   : "亮度蒙板",
            id     : $scope.TAB_ID.LUMINOSITY_MASKS,
            labels : {
                high   : "高光",
                mid    : "中间调",
                low    : "暗部",
                zone   : "区域",
                full   : "亮度"
            }
        },{
            name   : "饱和度蒙板",
            id     : $scope.TAB_ID.SATURATION_MASKS,
            labels : {
                high   : "高饱和",
                mid    : "中饱和",
                low    : "低饱和",
                zone   : "区域饱和",
                full   : "饱和度"
            }
        },{
            name   : "帮助支持",
            id     : $scope.TAB_ID.SUPPORT,
        }
    ]
    $scope.currentTab  = $scope.TABS[0];
    $scope.currentTool = $scope.TOOL_ID.TOOL_MENU;
    $scope.toolSliderValue     = "50"
    $scope.toolFineSliderValue = "20"
    $scope.csInterface = new CSInterface()
    $scope.PSVersion = $scope.csInterface.getHostEnvironment().appVersion.split('.')
    $scope.saturationMasksEnabled = 14 < $scope.PSVersion[0] 

    
    /*
     * Watch expressions to sync changes with backend
     */
    $scope.notifyToolSliderValueChange = function(){
        if ( $scope.currentTool == $scope.TOOL_ID.TOOL_HIGH ) {
            $scope.setHighValue(parseInt($scope.toolSliderValue))   
        } else if ( $scope.currentTool == $scope.TOOL_ID.TOOL_MID ) {
            $scope.setMidValue(parseInt($scope.toolSliderValue))  
        } else if ( $scope.currentTool == $scope.TOOL_ID.TOOL_LOW ) {
            $scope.setLowValue(parseInt($scope.toolSliderValue))   
        } else if ( $scope.currentTool == $scope.TOOL_ID.TOOL_ZONE ) {
            $scope.setZoneValue(parseInt($scope.toolSliderValue),
                                parseInt($scope.toolFineSliderValue)) 
        }
    }
    $scope.$watch("toolSliderValue", $scope.notifyToolSliderValueChange);
    $scope.$watch("currentTool", function(){
        $scope.notifyToolSliderValueChange()
    })
    $scope.$watch("toolFineSliderValue", function(){
        if ( $scope.currentTool == $scope.TOOL_ID.TOOL_ZONE ) {
            $scope.setZoneValue(parseInt($scope.toolSliderValue),
                                parseInt($scope.toolFineSliderValue))
        }
    })
    
    $scope.onLoad = function /* void */ () {
        // load theme manager
        themeManager.init();
        
        // make panel persistent
        var currentFileName = window.location.pathname
        var currentPathName = currentFileName.substring(0, currentFileName.lastIndexOf('/'));
        var debugFileName = currentPathName + "/.debug"
        $scope.fileExists(debugFileName, function (result) {
            if ( result == "false" ) {
                $scope.makePersistent()      
            }
        })
    }
    
    $scope.makePersistent = function () {
        /* make the panel persistent (i.e., it does not reload everytime we fold it away */
        var event = new CSEvent();
        event.type = "com.adobe.PhotoshopPersistent";
        event.scope = "APPLICATION";
        event.extensionId = window.__adobe_cep__.getExtensionId();
        $scope.csInterface.dispatchEvent(event);
    }

    $scope.haveDocument = function /* boolean */ (callback) {
        var command = "__ss_ilm_haveDocument()"
        $scope.csInterface.evalScript(command, function (result) {
            var resultValue = result == "true"
            callback(resultValue)
        })
    }

    $scope.showMessage = function /* void */ (msg) {
        var command = "__ss_ilm_showMessage(" + msg + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.showPrompt = function /* void */ (msg, value, callback) {
        var command = "__ss_ilm_showPrompt(\"" + msg + "\",\"" + value + "\")"
        $scope.csInterface.evalScript(command, callback);
    }

    $scope.createHighMask = function /* void */ () {
        var command = "__ss_ilm_action_createHighMask(" + $scope.currentTab.id + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createMidMask = function /* void */ () {
        var command = "__ss_ilm_action_createMidMask(" + $scope.currentTab.id + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createLowMask = function /* void */ () {
        var command = "__ss_ilm_action_createLowMask(" + $scope.currentTab.id + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createZoneMask = function /* void */ () {
        var command = "__ss_ilm_action_createZoneMask(" + $scope.currentTab.id + ")"
        $scope.csInterface.evalScript(command)
    }
    
    $scope.createFullMask = function /* void */ () {
        var command = "__ss_ilm_action_createFullMask(" + $scope.currentTab.id + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.deletIMLGroup = function /* void */ () {
        var command = "__ss_ilm_action_deleteIMLGroup()"
        $scope.csInterface.evalScript(command)
    }

    $scope.createSelection = function /* void */ () {
        var command = "__ss_ilm_action_createSelection()"
        $scope.csInterface.evalScript(command)
    }

    $scope.createChannel = function /* void */ (name) {
        var command = "__ss_ilm_action_createChannel(\"" + name + "\")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createCurves = function /* void */ (name) {
        var command = "__ss_ilm_action_createCurvesLayer(\"" + name + "\")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createLevels = function /* void */ (name) {
        var command = "__ss_ilm_action_createLevelsLayer(\"" + name + "\")"
        $scope.csInterface.evalScript(command)
    }

    $scope.createHueSaturation = function /* void */ (name) {
        var command = "__ss_ilm_action_createHueSaturationLayer(\"" + name + "\")"
        $scope.csInterface.evalScript(command)
    }

    $scope.selectLayer = function /* void */ (name) {
        var command = "__ss_ilm_action_selectLayer(\"" + name + "\")"
        $scope.csInterface.evalScript(command)
    }
    
    $scope.openURL = function /* void */ (url) {
        var command = "__ss_ilm_openURL(\"" + url + "\")"
        $scope.csInterface.evalScript(command)
    }
    
    $scope.fileExists = function /* void */ (filename, callback) {
        var command = "__ss_ilm_fileExists(\"" + filename + "\")"
        $scope.csInterface.evalScript(command, callback)
    }

    $scope.showMenu = function /* void */ () {
        $scope.currentTool = $scope.TOOL_ID.TOOL_MENU;
    }

    $scope.showToolDialog = function /* void */ (toolState, toolFn) {
        var deferredToolState = $q.defer()
        
        $scope.haveDocument(function (result) {
            if (result) {
                /* create layers */
                toolFn()
                
                /* switch to highlight tool */
                deferredToolState.resolve(toolState)
            } else {
                deferredToolState.reject()   
            }
        })
        
        // switch to current tab
        deferredToolState.promise.then(function (value) {
            $scope.currentTool = value
            $scope.toolSliderValue = "50"
        });
    }

    $scope.showHighMaskDialog = function /* void */ () {
        $scope.showToolDialog($scope.TOOL_ID.TOOL_HIGH, $scope.createHighMask)
    }
    
    $scope.showMidMaskDialog = function /* void */ () {
        $scope.showToolDialog($scope.TOOL_ID.TOOL_MID, $scope.createMidMask)
    }

    $scope.showLowMaskDialog = function /* void */ () {
        $scope.showToolDialog($scope.TOOL_ID.TOOL_LOW, $scope.createLowMask)
    }

    $scope.showZoneMaskDialog = function /* void */ () {
        $scope.showToolDialog($scope.TOOL_ID.TOOL_ZONE, $scope.createZoneMask)
        $scope.toolFineSliderValue = "20"
        
    }

    $scope.showFullMaskDialog = function /* void */ () {
        $scope.showToolDialog($scope.TOOL_ID.TOOL_FULL, $scope.createFullMask)
    }
    
    $scope.adjustToolSliderValueBy = function /* void */ (value) {
        var newToolSliderValue = parseInt($scope.toolSliderValue)
        newToolSliderValue += value
        newToolSliderValue = Math.max(0, newToolSliderValue)
        newToolSliderValue = Math.min(100, newToolSliderValue)
        $scope.toolSliderValue = ""+newToolSliderValue
    }

    $scope.onLtLt = function /* void */ onLtLt() {
        $scope.adjustToolSliderValueBy(-5)
    }

    $scope.onLt = function /* void */ () {
        $scope.adjustToolSliderValueBy(-1)
    }

    $scope.onGt = function /* void */ () {
        $scope.adjustToolSliderValueBy(1)
    }

    $scope.onGtGt = function /* void */ () {
        $scope.adjustToolSliderValueBy(5)
    }

    $scope.onSelection = function /* void */ () {
        $scope.createSelection();
        $scope.onCancel();
    }

    $scope.onChannel = function /* void */ () {
        var finished = $q.defer()
        $scope.showPrompt("Enter a name for the new channel", "MyChannel", function (name) {
            if (name) {
                $scope.createChannel(name)
            }
            finished.resolve()
        })
        finished.promise.then(function () {
            $scope.onCancel()
        })
    }

    $scope.onCurves = function /* void */ () {
        var finished = $q.defer()
        $scope.showPrompt("Enter a name for the new curves layer", "MyLayer", function (name) {
            if (name) {
                $scope.createCurves(name)
                $scope.selectLayer(name)
            }            
            finished.resolve()
        })
        finished.promise.then(function () {
            $scope.onCancel()
        })
    }

    $scope.onLevels = function /* void */ () {
        var finished = $q.defer()
        $scope.showPrompt("Enter a name for the new curves layer", "MyLayer", function (name) {
            if (name) {
                $scope.createLevels(name)
                $scope.selectLayer(name)
            }
            finished.resolve()
        })
        finished.promise.then(function () {
            $scope.onCancel()
        })
    }

    $scope.onHueSaturation = function /* void */ () {
        var finished = $q.defer()
        $scope.showPrompt("Enter a name for the new curves layer", "MyLayer", function (name) {
            if (name) {
                $scope.createHueSaturation(name)
                $scope.selectLayer(name)
            }
            finished.resolve()
        })
        finished.promise.then(function () {
            $scope.onCancel()
        })
    }

    $scope.onCancel = function /* void */ onCancel() {
        $scope.deletIMLGroup()
        $scope.showMenu()
    }

    $scope.setHighValue = function /* void */ (value) {
        var command = "__ss_ilm_setHighValue(" + value + ")"
        $scope.csInterface.evalScript(command)

    }

    $scope.setMidValue = function /* void */ (value) {
        var command = "__ss_ilm_setMidValue(" + value + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.setLowValue = function /* void */ (value) {
        var command = "__ss_ilm_setLowValue(" + value + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.setZoneValue = function /* void */ (toolSlideValue, toolFineSliderValue) {
        var command = "__ss_ilm_setZoneValue(" + toolSlideValue + "," + toolFineSliderValue + ")"
        $scope.csInterface.evalScript(command)
    }

    $scope.onColorPicker = function () {
        var zoneValueDefer = $q.defer()
        var command = "__ss_ilm_selectZoneFromUserColor(" + $scope.currentTab.id + "," + parseInt($scope.toolSliderValue) + ")"
        $scope.csInterface.evalScript(command, function (result) {
            if (result != "undefined") {
                zoneValueDefer.resolve(parseInt(result))
            } else {
                zoneValueDefer.reject()   
            }
        })
        zoneValueDefer.promise.then(function (value) {
            $scope.toolSliderValue = ""+value   
        })
    }

    $scope.onShowHomepage = function () {
        $scope.openURLInDefaultBrowser('http://www.svenstork.com');  
    }

    $scope.onShowOnlineHelp = function () {
        $scope.openURLInDefaultBrowser('http://svenstork.com/essays/interactive-luminosity-masks/');
    }
    
    $scope.onSupport = function () {
        $scope.openURLInDefaultBrowser('http://paypal.me/SvenStork');  
    }
    
    $scope.onFacebook = function () {
        $scope.openURLInDefaultBrowser('https://www.facebook.com/svenstorkphotography');  
    }
    
    $scope.onRate = function () {
        $scope.openURLInDefaultBrowser('https://creative.adobe.com/addons/products/12307');  
    }
    
    $scope.openURLInDefaultBrowser = function (url) {
        var majorVersion = parseInt($scope.PSVersion[0])
        if ( 15 <= majorVersion ) {
            $scope.csInterface.openURLInDefaultBrowser(url);  
        } else {
            $scope.openURL(url)
        }
    }
})
