(function () {
    'use strict';

    // コントローラ登録
    angular
        .module('app')
        .controller('SellController', Controller);

    // DI
    Controller.$inject = ['$log', '$timeout', '$cordovaCamera', 'BookService'];

    // コントローラ
    function Controller($log, $timeout, $cordovaCamera, BookService) {
        // ビューモデル
        var vm = this;
        vm.init = init;
        vm.getPicture = getPicture;
        vm.uploadBook = uploadBook;
        vm.goGrade = goGrade;

        vm.book = {
            name: '',
            school: {},
            campus: {},
            state: {},
            file: {
                dataUrl: null
            }
        };

        /**
         * 画像のリサイズ
         * @param {*} longSideMax 
         * @param {*} url 
         * @param {*} callback 
         */
        function resizeImage(longSideMax, url, callback) {
            var tempImg = new Image();
            tempImg.src = url;
            tempImg.onload = function () {
                var targetWidth = tempImg.width;
                var targetHeight = tempImg.height;
                var aspect = tempImg.width / tempImg.height;
                if (tempImg.width > tempImg.height) {
                    longSideMax = Math.min(tempImg.width, longSideMax);
                    targetWidth = longSideMax;
                    targetHeight = longSideMax / aspect;
                }
                else {
                    longSideMax = Math.min(tempImg.height, longSideMax);
                    targetHeight = longSideMax;
                    targetWidth = longSideMax * aspect;
                }
                var canvas = document.createElement('canvas');
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0, tempImg.width, tempImg.height, 0, 0, targetWidth, targetHeight);
                callback(canvas.toDataURL("image/jpeg"));
            };
        }

        /**
         * 写真撮影
         */
        function getPicture() {
            var options = {
                targetWidth: 640,
                targetHeight: 640,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                encodingType: Camera.EncodingType.JPEG,
                saveToPhotoAlbum: false,
                correctOrientation: true,
                quality: 80,
            };

            // 撮影
            $cordovaCamera.getPicture(options).then(function (imageData) {
                var dataUrl = 'data:image/jpeg;base64,' + imageData;
                resizeImage(160, dataUrl, function (result) {
                    $timeout(function () {
                        vm.book.thumbnail = result;
                    });
                });
                vm.book.file = {
                    dataUrl: dataUrl
                };
            }, function (err) {
                $log.error(err);
            }).finally(function () {
                $cordovaCamera.cleanup();
            });
        }

        /**
         * アップロード
         */
        function uploadBook() {
            var labels = ['キャンセル', '出品する'];
            ons.notification.confirm({
                message: 'この内容で出品しますか？',
                title: '確認',
                buttonLabels: labels,
                callback: function (index) {
                    if (index === labels.indexOf('出品する')) {
                        modal.show();
                        vm.book.state = 0;
                        BookService.uploadBook(vm.book).then(function (response) {
                            navi.pushPage("pages/sell/sell-complete.html");
                        }, function (error) {
                            $log.error(error);
                        }).finally(function () {
                            modal.hide();
                        });
                    }
                }
            });
        }

        /**
         * 商品状態設定画面に遷移
         */
        function goGrade() {
            var options = {
                data: {
                    grade: vm.book.grade,
                    update: function (data) {
                        vm.book.grade = data.grade.code;
                    }
                }
            }
            navi.pushPage('pages/common/select-item-grade.html', options);
        }

        // 初期化
        function init() {
        }
    }
})();
