/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 * This module provides the interface to an extenal IDE: Simplicity Studio.
 *
 * @module External IDE interface.
 */

const restApi = require('../../src-shared/rest-api.js')
const env = require('../util/env.js')
const importJs = require('../importexport/import.js')
const exportJs = require('../importexport/export.js')
const path = require('path')
const http = require('http-status-codes')
const querySession = require('../db/query-session.js')
const dbEnum = require('../../src-shared/db-enum.js')
const studio = require('../ide-integration/studio-rest-api.js')

/**
 * HTTP POST: IDE open
 *
 * @param {*} db
 * @returns callback for the express uri registration
 */
function httpPostFileOpen(db) {
  return (req, res) => {
    let zapPath = req.body.path
    if (zapPath != null) {
      let name = path.posix.basename(zapPath)
      let zapFile = zapPath

      env.logInfo(`Studio: Opening/Loading project(${name})`)

      importJs
        .importDataFromFile(db, zapFile, req.zapSessionId)
        .then((importResult) => {
          let response = {
            sessionId: importResult.sessionId,
            sessionKey: req.session.id,
          }
          env.logInfo(
            `Studio: Loaded project(${name}), ${JSON.stringify(response)}`
          )
          res.send(response)
        })
        .catch(function (err) {
          err.project = zapFile
          studio.sendSessionCreationErrorStatus(err)
          env.logError(JSON.stringify(err))
          res.status(http.StatusCodes.BAD_REQUEST).send(err)
        })
    } else {
      let msg = `Opening/Loading project: Missing path data.`
      env.logWarning(msg)
      res.status(http.StatusCodes.BAD_REQUEST).send({ error: msg })
    }
  }
}

/**
 * HTTP POST: IDE save
 *
 * @param {*} db
 * @returns callback for the express uri registration
 */
function httpPostFileSave(db) {
  return (req, res) => {
    let zapPath = req.body.path
    env.logInfo(`Saving session: id = ${req.zapSessionId}. path=${zapPath}`)

    let p
    if (zapPath == null) {
      p = querySession.getSessionKeyValue(
        db,
        req.zapSessionId,
        dbEnum.sessionKey.filePath
      )
    } else {
      p = querySession
        .updateSessionKeyValue(
          db,
          req.zapSessionId,
          dbEnum.sessionKey.filePath,
          zapPath
        )
        .then(() => zapPath)
    }

    p.then((path) => {
      return exportJs.exportDataIntoFile(db, req.zapSessionId, path)
    })
      .then((filePath) => {
        let projectName = path.posix.basename(filePath)
        env.logInfo(`Saving file: file = ${projectName}`)
        res.status(http.StatusCodes.OK).send({ filePath: filePath })
      })
      .catch((err) => {
        let msg = `Unable to save project with sessionId(${req.zapSessionId})`
        env.logError(msg)
        env.logError(err)
        res.status(http.StatusCodes.BAD_REQUEST).send({
          error: msg,
        })
      })
  }
}

exports.post = [
  {
    uri: restApi.ide.open,
    callback: httpPostFileOpen,
  },
  {
    uri: restApi.ide.save,
    callback: httpPostFileSave,
  },
]

@@ -3013,17 +3013,23 @@
 p.then((
-p
+actualP
 ath) =%3E 
@@ -3040,23 +3040,61 @@
     
-return exportJs
+if (actualPath != null) %7B%0A        exportJs%0A          
 .exp
@@ -3131,17 +3131,23 @@
 sionId, 
-p
+actualP
 ath)%0A   
@@ -3143,27 +3143,24 @@
 alPath)%0A    
-%7D)%0A
       .then(
@@ -3179,24 +3179,28 @@
 %3E %7B%0A        
+    
 let projectN
@@ -3231,24 +3231,28 @@
 e(filePath)%0A
+    
         env.
@@ -3297,32 +3297,36 @@
 Name%7D%60)%0A        
+    
 res.status(http.
@@ -3366,24 +3366,28 @@
 filePath %7D)%0A
+    
       %7D)%0A   
@@ -3385,24 +3385,28 @@
    %7D)%0A      
+    
 .catch((err)
@@ -3407,24 +3407,28 @@
 ((err) =%3E %7B%0A
+    
         let 
@@ -3494,32 +3494,36 @@
 onId%7D)%60%0A        
+    
 env.logError(msg
@@ -3524,32 +3524,36 @@
 or(msg)%0A        
+   
+ 
 env.logError(err
@@ -3550,24 +3550,28 @@
 gError(err)%0A
+    
         res.
@@ -3624,16 +3624,20 @@
         
+    
 error: m
@@ -3644,29 +3644,176 @@
 sg,%0A        
+    
 %7D)%0A  
+        %7D)%0A      %7D else %7B%0A        res%0A          .status(http.StatusCodes.BAD_REQUEST)%0A          .send(%7B error: 'No file specified.' %7D)%0A      %7D%0A
     %7D)%0A  %7D%0A%7D

Deal with unknown file correctly.