'use babel';

/**
 * Copyright (C) 2016 Ivan Kravets. All rights reserved.
 *
 * This source file is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import child_process from 'child_process';
import {SerialMonitorView} from './view';
import {openTerminal} from '../maintenance';

const BAUDRATE_KEY = 'platformio-ide:serial-monitor-baudrate';
const PORT_KEY = 'platformio-ide:serial-monitor-port';

export function command() {
  // Initialize view
  var view = new SerialMonitorView();
  var panel = atom.workspace.addModalPanel({item: view.getElement()});

  // Set buttons handlers
  view.handleCancel = () => panel.destroy();
  view.handleOpen = () => {
    localStorage.setItem(PORT_KEY, view.getPort());
    localStorage.setItem(BAUDRATE_KEY, view.getBaudrate());
    let command = `pio -f -c atom serialports monitor`;
    const settings = view.getAllSettings();
    for (let key of Object.keys(settings)) {
      command += ` --${key} ${settings[key]}`;
    }

    openTerminal(command);
    panel.destroy();
  };

  const defaultBaudrate = parseInt(localStorage.getItem(BAUDRATE_KEY) || '9600');
  view.setBaudrate(defaultBaudrate);

  return new Promise((resolve, reject) => {
    // Set ports
    const portsProcess = child_process.spawn('platformio', ['-f', '-c', 'atom', 'serialports', 'list', '--json-output']);
    let portsRawStdout = '';
    portsProcess.stdout.on('data', (chunk) => portsRawStdout += chunk);
    portsProcess.on('close', (code) => {
      if (0 !== code) {
        let title = 'PlaftormIO: Unable to get a list of serial ports.';
        atom.notifications.addError(title, {dismissable: true});
        console.error(title);
        reject();
      }
      view.setPorts(JSON.parse(portsRawStdout));
      resolve();
    });
  }).then(() => {
    // Set default port
    const defaultPort = localStorage.getItem(PORT_KEY);
    view.setDefaultPort(defaultPort);
  });
}

@@ -735,51 +735,8 @@
 */%0A%0A
-import child_process from 'child_process';%0A
 impo
@@ -817,16 +817,51 @@
 enance';
+%0Aimport %7BspawnPio%7D from '../utils';
 %0A%0Aconst 
@@ -1729,140 +1729,18 @@
 urn 
-new Promise((resolve, reject) =%3E %7B%0A    // Set ports%0A    const portsProcess = child_process.spawn('platformio', %5B'-f', '-c', 'atom', 
+spawnPio(%5B
 'ser
@@ -1779,186 +1779,135 @@
 t'%5D)
-;
 %0A    
-let portsRawStdout = '';%0A    portsProcess.stdout.on('data', (chunk) =%3E portsRawStdout += chunk);%0A    portsProcess.on('close', (code) =%3E %7B%0A      if (0 !== code) %7B%0A        le
+.then(function onSuccess(output) %7B%0A      view.setPorts(JSON.parse(output));%0A    %7D, function onFailure(reason) %7B%0A      cons
 t ti
@@ -1971,18 +1971,16 @@
 ;%0A      
-  
 atom.not
@@ -2030,26 +2030,24 @@
 ue%7D);%0A      
- 
- 
 console.erro
@@ -2066,106 +2066,50 @@
     
-  reject();%0A      %7D%0A      view.setPorts(JSON.parse(portsRawStdout));%0A      resolve();%0A    %7D);%0A  %7D)
+return Promise.reject(reason);%0A    %7D)%0A    
 .the
@@ -2114,24 +2114,26 @@
 hen(() =%3E %7B%0A
+  
     // Set d
@@ -2144,24 +2144,26 @@
 lt port%0A    
+  
 const defaul
@@ -2202,24 +2202,26 @@
 T_KEY);%0A    
+  
 view.setDefa
@@ -2242,16 +2242,18 @@
 tPort);%0A
+  
   %7D);%0A%7D%0A

Use "spawnPio" for Serial Monitor command