# -*- coding: utf-8 -*-
"""
/***************************************************************************
 LiDARForestryHeight
                                 A QGIS plugin. LiDAR Forestry Height
                                 generates a DEM with the forest height,
                                 calculated from a classified LiDAR point
                                 cloud using LasPy Library

 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2018-09-24
        copyright            : (C) 2019 by PANOimagen S.L.
        email                : info@panoimagen.com
        git sha              : $Format:%H$
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os
import subprocess

def run_LASzip(laz_path):
    """ This function call executable laszip file and unzip lidar file (*.las)
        to *.las. LASzip is an external software with LGPL License. For more
        information visit https://rapidlasso.com/laszip/
    """
    
    path = os.path.split(os.path.abspath(__file__))[0]
    LASzip_path = os.path.join(path, 'LASzip', 'laszip64.exe')

    laz_dir, laz_file = os.path.split(laz_path)
    laz_filename, laz_ext = os.path.splitext(laz_file)
    
    las_ext = '.las'
    idx = 0
    las_path = os.path.join(laz_dir, (laz_filename + '_{}'.format(idx) + 
                                          las_ext))
# -----------------------------------------------------------------------------

    in_args = ' -i {}'.format(laz_path)
    out_args = ' -o {}'.format(las_path)

    call = LASzip_path + in_args + out_args

    shell  = False
    ret = subprocess.call(call, shell)

    if ret !=0:
        if ret < 0:
            raise ValueError(u'LASzip process killed by signal.' + 
                            u' Return code: {}'.format(-ret))
        else:
            raise ValueError(u'LASzip process failed. Return code: {}'.format(
                    ret))
    else:
        return True, las_path