///define(['app'], function (app) {
(function () {

  var app = angular.module("myApp");

  app.factory("VS4Library", [
    '$rootScope', '$window', '$http', '$q', '$location', '$sce', 'ngDialog', 'moment',
    function ($rootScope, $window, $http, $q, $location, $sce, ngDialog, moment) {

      var svc = {};

      svc.AppVersion = function () {
        return 0.2;
      };

      svc.init = function () {
        $rootScope.isReady = true;
        $rootScope.apiBase = '';
        $http.get('/web.config.json').then(function (response) {
          $rootScope.apiBase = '' + response.data.apiBase;
        }, function (error) {
          $rootScope.apiBase = '';
        });
        $rootScope.ActiveUser = $window.sessionStorage.ActiveUser;
        $rootScope.isLogin = ($window.sessionStorage.isLogin === "true");
        $rootScope.isStaff = ($window.sessionStorage.isStaff === "true");
        $rootScope.forceReload = svc.RandomString(10).toUpperCase();

        $rootScope.progressOpts = {
          lines: 11,
          length: 11,
          width: 3,
          radius: 15,
          corners: 1,
          rotate: 0,
          direction: 1,
          color: '#000',
          speed: 1,
          trail: 60,
          shadow: false,
          hwaccel: false,
          className: 'spinner',
          zIndex: 2e9,
          top: '50%',
          left: '50%'
        };


        return "";
      };

      //			svc.getValueINI = function (uri, keyId) {
      //				$rootScope.tempReadDataINI = '';
      //				$http.get(uri).then(function (response) {
      //					$rootScope.tempReadDataINI = '' + response.data[keyId];
      //				},function (error) {
      //					$rootScope.tempReadDataINI = '';
      //				})
      //				return $rootScope.tempReadDataINI;
      //			};


      svc.Login = function (data) {
        return $http.post($rootScope.apiBase + '/api/System/Login', data);
      };


      svc.LoadData = function (iQuery, iUrl) {
        if (iUrl !== "") {

          var dataManger = ej.DataManager({
            url: iUrl
            //,offline: true
          });
          //var query = new ej.Query();
          var dm = dataManger.executeQuery(iQuery); //Request the webservice
          dm.done(function (e) {
            return e.result;
          })
            .error(function (e) {
              return [];
            });
        }
        return [];
      };


      svc.SetToken = function () {
        $http.defaults.headers.common['authenticationToken'] = $window.sessionStorage.ActiveUser + "#" + $window.sessionStorage.token;
        return "";
      };

      svc.RandomString = function (ilength) {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0; i < ilength; i++)
          text += possible.charAt(Math.floor(Math.random() * possible.length));
        return text;
      };

      svc.GetValueByValue = function (obj, value, defaultValue) {
        for (var i = 0; i < obj.length; i++) {
          if (obj[i].value == value) {
            return obj[i].value;
          }
        }
        return defaultValue;
      };

      svc.GetTextByValue = function (obj, value) {
        for (var i = 0; i < obj.length; i++) {
          if (obj[i].value == value) {
            return obj[i].text;
          }
        }
        return "";
      };

      svc.GetValueByText = function (obj, text) {
        for (var i = 0; i < obj.length; i++) {
          if (obj[i].text == text) {
            return obj[i].value;
          }
        }
        return "";
      };

      svc.GetDateText = function () {
        return moment().format("D/M/YYYY");
      };

      svc.GetDateQuery = function () {
        return moment().format("YYYY-MM-DD");
      };

      svc.GetDateTimeStamp = function (minimum) {
        if (minimum === undefined) {
          return moment().format("YYYY-MM-DDTHH:MM:SS");
        } else {
          return moment().format("YYYYMMDDHHMMSS");
        }
      };

      svc.GetMonthYear = function () {
        var d = svc.GetDate();
        d.setDate(1);
        return d;
      };

      svc.GetMonthYearText = function () {
        var d = svc.GetDate();
        d.setDate(1);
        return moment(d).format("D/M/YYYY");
      };

      svc.GetCTYear = function () {
        var y = Number(moment().format("YYYY"));
        y += 543;
        return "" + y;
      };

      svc.GetDate = function () {
        var now = svc.GetNow();
        now.setHours(0, 0, 0, 0);
        return now;
      };

      svc.GetNow = function () {
        var now = new Date();
        //var now = new Date(now2.valueOf() - (now2.getTimezoneOffset() * 60000));
        //var now = new Date(Date.UTC(now2.getFullYear(), now2.getMonth(), now2.getDate(), now2.getHours(), now2.getMinutes(), now2.getSeconds()));
        return now;
      };

      svc.GetWorkingDate = function () {
        if ($window.sessionStorage.WorkingDate === undefined) {
          $window.sessionStorage.WorkingDate = new Date();
          $window.sessionStorage.WorkingDate = svc.GetDate();
        }
        return $window.sessionStorage.WorkingDate;
      };

      svc.cDate = function (txtDate, format) {
        if (format === undefined) {
          format = 'D/M/YYYY';
        }
        try {
          var d = txtDate.getDate();
          return d;
        }
        catch (ex) {
          var valid = moment(txtDate, format).isValid();
          if (valid) {
            return moment(txtDate, format).toDate();
          } else {
            return new Date();
          }
        }
      };

      svc.isDate = function (txtDate, format) {
        if (format === undefined) {
          format = 'D/M/YYYY';
        }
        var valid = moment(txtDate, format).isValid();
        return valid;
      };

      svc.formatDate2Query = function (iDate) {
        var dateQuery = moment(iDate).format("YYYY-MM-DD")
        return dateQuery;
      };

      svc.formatTextDate2Query = function (txtDate, format) {
        var iDate = svc.cDate(txtDate, format);
        var dateQuery = moment(iDate).format("YYYY-MM-DD")
        return dateQuery;
      };

      svc.cInt = function (txt) {
        var txt1 = svc.cStr(txt);
        //txt1 = txt.toString();
        var v = svc.cDbl(txt1.replace(/,/g, "").trim());
        return v.toFixed(0);
      };

      svc.cDbl = function (txt) {
        var txt1 = svc.cStr(txt);
        //txt1 = txt.toString();
        var v = Number(txt1.replace(/,/g, "").trim());
        if (v === NaN) {
          v = 0;
        }
        return v;
      };

      svc.cStr = function (txt) {
        if (txt === undefined || txt === NaN || txt === null) { return ""; }
        else { }
        return txt.toString();
      };

      svc.formatFilterP = function (iValue, iconditionName, iValidData, iDefaultValue, iValueFormat, iconditionLabel) {
        pp = "";
        vv = iValue;
        // tt = "";
        // if (iValidData !== undefined && iValidData !== null) {
        //   vv = VS4Library.GetValueByValue($scope.formData.filter02dataList,vv,iDefaultValue);
        //   tt = VS4Library.GetTextByValue($scope.formData.filter02dataList,vv);
        // }
        if (iValueFormat !== "" && iValueFormat !== undefined && iValueFormat !== null) {
          if (iconditionLabel !== undefined && iconditionLabel !== null) {
            pp = ";" + iconditionName + "=" + vv;
            pp += ";" + iconditionName + "_F" + "=" + iValueFormat;
          } else {
            pp = ";" + iconditionName + "=" + vv;
            pp += ";" + iconditionName + "_F" + "=" + iValueFormat;
          }
        } else {
          // if (tt !== ""){
          //   pp = ";" + iconditionName + "=" + vv;
          //   pp += ";" + iconditionName + "_F" + "=" + tt;
          // }else{
          pp = ";" + iconditionName + "=" + vv;
          // }
        };
        return pp;
      }

      // ifieldType = D(Date), T(Time), DT(DateTime), S(String), I(Int)
      svc.formatFilter = function (formData, ifieldType, iRequire, iFieldName, iCondition, iValue, iconditionName, iValidData, iDefaultValue, iValueFormat, iconditionLabel) {
        p = "";
        o = "";
        t = "";
        f = "";
        // var f = iFieldName.split(".");
        // fn = f[f.length-1];
        fn = "";
        if (iconditionName !== undefined && iconditionName !== null) {
          fn = iconditionName
        };
        v = "";
        if (iValue !== undefined && iValue !== null) {
          v = iValue;
        };
        if (iValueFormat !== undefined && iValueFormat !== null) {
          f = iValueFormat;
        };
        if (iValidData !== undefined && iValidData !== null) {
          v = svc.GetValueByValue(iValidData, v, iDefaultValue);
          f = svc.GetTextByValue(iValidData, v);
        }

        switch (ifieldType) {
          case "D":
          case "Date":
            if (iRequire === true) {
              if (!svc.isDate(v)) {
                t = svc.GetDateText();
              } else {
                t = svc.cDate(v);
              }
              //o = " AND DATEADD(dd, DATEDIFF(dd, 0, " + iFieldName + "), 0) " + iCondition + " " + "'" + VS4Library.formatDate2Query(t) + "'";
              o = " AND " + iFieldName + " " + iCondition + " " + "'" + svc.formatDate2Query(t) + "'";
              p = ";" + fn + "=" + svc.formatDate2Query(t);
            } else {
              if (v !== "") {
                if (svc.isDate(v)) {
                  //o = " AND DATEADD(dd, DATEDIFF(dd, 0, " + iFieldName + "), 0) " + iCondition + " " + "'" + VS4Library.formatTextDate2Query(v) + "'";
                  o = " AND " + iFieldName + " " + iCondition + " " + "'" + svc.formatTextDate2Query(v) + "'";
                  p = ";" + fn + "=" + svc.formatTextDate2Query(v);
                }
              }
            }
            break;
          // case "T":
          // case "Time":
          //   break;
          //
          // case "DT":
          // case "DateTime":
          //   break;
          //
          case "I":
          case "Int":
          case "N0":
          case "Number0":
            if (iRequire === true) {
              y = svc.cInt(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = svc.cInt(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "A":
          case "N2":
          case "Number2":
            if (iRequire === true) {
              y = svc.cDbl(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = svc.cDbl(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "V":
          case "E":
          case "N5":
          case "Number5":
            if (iRequire === true) {
              y = svc.cDbl(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = svc.cDbl(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "P":
            p = ";" + fn + "=" + v;
            break;

          default:
            if (iRequire === true) {
              o = " AND " + iFieldName + " " + iCondition + " " + "'" + v + "'";
              p = svc.formatFilterP(v, fn, iValidData, iDefaultValue, f, iconditionLabel);
            } else {
              if (v !== "") {
                o = " AND " + iFieldName + " " + iCondition + " " + "'" + v + "'";
              }
              p = svc.formatFilterP(v, fn, iValidData, iDefaultValue, f, iconditionLabel);
            }
        }
        formData.where += o;
        if (p !== "" && fn !== "") {
          formData.reportConditions += p;
        }
        return o;
      }

      return svc;
    }
  ]);


  ///});
})();

String.prototype.left = function (n) {
  return this.substring(0, n);
}

String.prototype.right = function (n) {
  var l = this.length;
  var o = this.substring(l - n);
  return o;
}