// Generated by CoffeeScript 1.7.1
(function() {
  var Datastore, child_process, crypto, db, fs, gui, mkdirp, path, rmdir;

  path = require('path');

  fs = require('fs');

  child_process = require('child_process');

  crypto = require('crypto');

  mkdirp = require('mkdirp');

  rmdir = require('rmdir');

  gui = require('nw.gui');

  Datastore = require('nw_nedb');

  db = {
    apps: new Datastore({
      filename: path.join(gui.App.dataPath, 'apps.db'),
      autoload: true
    }),
    local: new Datastore({
      filename: path.join(gui.App.dataPath, 'local.db'),
      autoload: true
    }),
    profile: new Datastore({
      filename: path.join(gui.App.dataPath, 'profile.db'),
      autoload: true
    })
  };

  angular.module('maotama.controllers', []).controller('AppsListController', [
    '$scope', '$routeParams', '$http', '$location', function($scope, $routeParams, $http, $location) {
      $scope.orderProp = 'id';
      $http.get('apps.json').success(function(data) {
        return db.apps.remove({}, {
          multi: true
        }, function(err, numRemoved) {
          if (err) {
            throw err;
          }
          return db.apps.insert(data, function(err, newDocs) {
            if (err) {
              throw err;
            }
            $scope.apps = data;
            if (!$routeParams.app_id) {
              $location.path("/apps/" + data[0].id);
              return $scope.$apply();
            } else {
              return $scope.$digest();
            }
          });
        });
      });
      $scope.active = function(app_id) {
        if ($routeParams.app_id === app_id) {
          return "active";
        }
      };
      return $scope.category_active = function(category) {
        var a, app, _i, _len, _ref;
        if ($scope.apps) {
          app = null;
          _ref = $scope.apps;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            a = _ref[_i];
            if (a.id === $routeParams.app_id) {
              app = a;
            }
          }
          if (app) {
            if (app.category === category) {
              return "active";
            }
          }
        }
      };
    }
  ]).controller('AppsShowController', [
    '$scope', '$routeParams', function($scope, $routeParams) {
      db.apps.findOne({
        id: $routeParams.app_id
      }, function(err, doc) {
        if (err) {
          throw err;
        }
        $scope.app = doc;
        $scope.runtime = {
          running: false,
          installing: {}
        };
        $scope.default_installation_path = path.join(process.cwd(), 'apps', $scope.app.id);
        return db.local.findOne({
          id: $routeParams.app_id
        }, function(err, doc) {
          $scope.local = doc != null ? doc : {};
          return db.profile.findOne({
            id: $routeParams.app_id
          }, function(err, doc) {
            var achievement;
            if (doc) {
              $scope.profile = doc;
              return $scope.$digest();
            } else {
              $scope.profile = {
                id: $routeParams.app_id,
                achievements: $scope.app.achievements ? (function() {
                  var _i, _len, _ref, _results;
                  _ref = $scope.app.achievements;
                  _results = [];
                  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                    achievement = _ref[_i];
                    _results.push([]);
                  }
                  return _results;
                })() : void 0
              };
              return db.profile.insert($scope.profile, function(err, newDoc) {
                if (err) {
                  throw err;
                }
                return $scope.$digest();
              });
            }
          });
        });
      });
      $scope.add = function(installation) {
        $scope.local.installation = path.dirname(installation);
        return db.local.update({
          id: $scope.app.id
        }, {
          $set: {
            installation: $scope.local.installation
          }
        }, {
          upsert: true
        }, function(err, numReplaced, newDoc) {
          if (err) {
            throw err;
          }
          return $scope.$digest();
        });
      };
      $scope.install = function() {
        $scope.runtime.installing[$scope.app.id] = {
          process: 0,
          label: '正在连接'
        };
        return mkdirp(path.join(process.cwd(), 'cache'), function(err) {
          var aria2c;
          if (err) {
            throw err;
          }
          aria2c = child_process.spawn('bin/aria2c', ["--check-integrity", "--checksum=md5=" + $scope.app.download.checksum, "--dir=cache", "--enable-color=false", "-c", $scope.app.download.url]);
          aria2c.stdout.setEncoding('utf8');
          aria2c.stderr.setEncoding('utf8');
          aria2c.stdout.on('data', function(data) {
            var connections, d, downloaded, eta, matches, progress, speed, total;
            console.log(data);
            if (matches = data.match(/\[(?:#\w+ )?([\w\.]+)\/([\w\.]+)\((\d+)%\) CN:(\d+) DL:([\w\.]+) ETA:(\w+)\]/)) {
              d = matches[0], downloaded = matches[1], total = matches[2], progress = matches[3], connections = matches[4], speed = matches[5], eta = matches[6];
              $scope.runtime.installing[$scope.app.id].progress = progress;
              $scope.runtime.installing[$scope.app.id].label = "" + progress + "% " + speed + "/s";
              return $scope.$digest();
            }
          });
          aria2c.stderr.on('data', function(data) {
            return console.log('err: ', data);
          });
          return aria2c.on('close', function(code) {
            var checksum, downloaded, file;
            if (code !== 0) {
              window.LOCAL_NW.desktopNotifications.notify($scope.app.icon, $scope.app.name, "下载失败, 错误: " + code);
              delete $scope.runtime.installing[$scope.app.id];
              return $scope.$digest();
            } else {
              $scope.runtime.installing[$scope.app.id].progress = 100;
              $scope.runtime.installing[$scope.app.id].label = '正在安装';
              $scope.$digest();
              downloaded = "cache/" + (path.basename($scope.app.download.url));
              checksum = crypto.createHash('md5');
              file = fs.ReadStream(downloaded);
              file.on('data', function(d) {
                return checksum.update(d);
              });
              return file.on('end', function() {
                var p;
                if (checksum.digest('hex') !== $scope.app.download.checksum) {
                  window.LOCAL_NW.desktopNotifications.notify($scope.app.icon, $scope.app.name, "校验错误");
                  delete $scope.runtime.installing[$scope.app.id];
                  return $scope.$digest();
                } else {
                  p = path.join("apps/" + $scope.app.id);
                  return mkdirp(p, function(err) {
                    var p7zip;
                    if (err) {
                      throw err;
                    }
                    console.log(["x", "-y", "-o" + p, downloaded]);
                    console.log(p7zip = child_process.spawn('bin/7za', ["x", "-y", "-o" + p, "cache/" + (path.basename($scope.app.download.url))]));
                    p7zip.stdout.setEncoding('utf8');
                    p7zip.stderr.setEncoding('utf8');
                    p7zip.stdout.on('data', function(data) {
                      return console.log(data);
                    });
                    p7zip.stderr.on('data', function(data) {
                      return console.log('err: ', data);
                    });
                    return p7zip.on('close', function(code) {
                      if (code !== 0) {
                        window.LOCAL_NW.desktopNotifications.notify($scope.app.icon, $scope.app.name, "安装失败, 错误: " + code);
                        delete $scope.runtime.installing[$scope.app.id];
                        return $scope.$digest();
                      } else {
                        delete $scope.runtime.installing[$scope.app.id];
                        window.LOCAL_NW.desktopNotifications.notify($scope.app.icon, $scope.app.name, '安装完成');
                        return $scope.add(path.join(p, $scope.app.main));
                      }
                    });
                  });
                }
              });
            }
          });
        });
      };
      $scope.uninstall = function() {
        $scope.runtime.uninstalling = true;
        return db.local.remove({
          id: $scope.app.id
        }, function(err, numRemoved) {
          if (err) {
            throw err;
          }
          return rmdir($scope.local.installation, function(err, dirs, files) {
            console.log(dirs);
            console.log(files);
            console.log('all files are removed');
            $scope.local = {};
            return $scope.$digest();
          });
        });
      };
      $scope.run = function() {
        var game;
        $scope.runtime.running = true;
        game = child_process.spawn($scope.app.main, [], {
          cwd: $scope.local.installation
        });
        game.stdout.setEncoding('utf8');
        game.stdout.on('data', function(data) {
          var achievement, achievement_item, command, matches, _base, _i, _len, _name, _ref;
          console.log(data);
          if (matches = data.match(/<maotama>(.+)<\/maotama>/)) {
            _ref = $(matches[1]);
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              command = _ref[_i];
              switch (command.tagName) {
                case 'ACHIEVEMENT':
                  achievement = $scope.app.achievements[$(command).attr('type')];
                  achievement_item = achievement.items[$(command).attr('id')];
                  if ((_base = $scope.profile.achievements)[_name = $(command).attr('type')] == null) {
                    _base[_name] = {};
                  }
                  if ($scope.profile.achievements[$(command).attr('type')][$(command).attr('id')]) {
                    return;
                  }
                  window.LOCAL_NW.desktopNotifications.notify(achievement_item.icon, "获得" + achievement.name + ": " + achievement_item.name, achievement_item.description);
                  $scope.profile.achievements[$(command).attr('type')][$(command).attr('id')] = {
                    created_at: new Date(),
                    updated_at: new Date(),
                    count: 1
                  };
                  db.profile.update({
                    id: $scope.app.id
                  }, $scope.profile, function(err, numReplaced, newDoc) {
                    if (err) {
                      throw err;
                    }
                    return $scope.$digest();
                  });
                  break;
                default:
                  window.LOCAL_NW.desktopNotifications.notify($scope.app.icon, "unknown command", matches[1]);
              }
            }
          }
        });
        return game.on('close', function(code) {
          $scope.runtime.running = false;
          return $scope.$digest();
        });
      };
      $scope.achievement_unlocked_count = function(category) {
        return $scope.profile.achievements[category].length;
      };
      $scope.achievement_total_count = function(category) {
        return $scope.app.achievements[category].items.length;
      };
      $scope.achievement_last_unlocked = function(category) {
        var achievement, index, last, last_index, _ref;
        last = null;
        last_index = null;
        _ref = $scope.profile.achievements[category];
        for (index in _ref) {
          achievement = _ref[index];
          if (!last || result.created_at < last.created_at) {
            last = achievement;
            last_index = index;
          }
        }
        return $scope.app.achievements[category].items[index];
      };
      return $scope.achievement_locked = function(category, index) {
        if ($scope.profile.achievements[category][index]) {
          return '';
        } else {
          return 'locked';
        }
      };
    }
  ]);

}).call(this);

//# sourceMappingURL=controllers.map
