// Copyright (c) 2015 Alejandro Blanco <alejandro.b.e@gmail.com>
// MIT License

/* global sjcl */

import Ember from 'ember';

export default Ember.Controller.extend({
    notReadyToSave: Ember.computed('tempPassword', function () {
        return Ember.isEmpty(this.get('tempPassword'));
    }),

    completeSave: function (masterPassword) {
        var that = this,
            reference,
            ciphered;

        if (this.get('allPasswords.length') > 0) {
            reference = this.get('allPasswords.firstObject.secret');
            try {
                sjcl.decrypt(masterPassword, reference);
            } catch (err) {
                // TODO wrong master password
                return;
            }
        }

        try {
            ciphered = sjcl.encrypt(masterPassword, this.get('tempPassword'));
        } catch (err) {
            // TODO
        }
        this.set('model.creation', new Date());
        this.set('model.secret', ciphered);
        masterPassword = null;

        this.get('model').save().then(function () {
            that.transitionToRoute('passwords.index');
        });
    },

    actions: {
        updatePassword: function (newPassword) {
            this.set('tempPassword', newPassword);
        },

        updateTags: function (newTags) {
            this.set('tags', newTags);
        },

        sendMasterPassword: function (masterPassword) {
            this.set('requestMasterPassword', false);
            // TODO save temporal copy of the masterPassword if necessary
            this.completeSave(masterPassword);
        },

        save: function () {
            this.set('requestMasterPassword', true);
        }
    }
});

@@ -363,16 +363,40 @@
 = this,%0A
+            withSecret,%0A
         
@@ -445,12 +445,21 @@
     
-if (
+withSecret = 
 this
@@ -476,17 +476,143 @@
 asswords
-.
+').filter(function (password) %7B%0A            return password.get('secret.length') %3E 0;%0A        %7D);%0A%0A        if (withSecret.get('
 length')
@@ -647,31 +647,24 @@
 e = 
-this.get('allPasswords.
+withSecret.get('
 firs

Fix master password validation in creation