# %%
from skimage.transform import probabilistic_hough_line
import os
import subprocess
# %%
import pdal
import json
import geopandas as gpd
import rasterio as rio
import pandas as pd
import numpy as np
from shapely.geometry import Point
import dask.dataframe as dd
from rasterio.features import rasterize
# %%
lasfile = '/media/data/WRTC/powerline/FG1_0_-1_classified.laz'
basename = os.path.basename(lasfile).partition('.')[0]
tmppath = os.path.join(os.path.dirname(lasfile), 'tmp')
rasfile = os.path.join(tmppath, basename + '.tif')
jsonpath = os.path.join(tmppath, basename + '.json')
out_laz = os.path.join(tmppath, f'{basename}_trimmed.laz')

os.makedirs(tmppath, exist_ok=True)
# %%



def grep_intensity(lasfile):
    cmd = f'pdal info {lasfile}'
    _ = subprocess.run(cmd, shell=True, capture_output=True)
    j = json.loads(_.stdout)
    I = [d for d in j['stats']['statistic'] if d['name'] == 'Intensity'][0]
    I_min = I['minimum']
    I_max = I['average'] + I['stddev']
    return(I_min, I_max)

I_min, I_max = grep_intensity(lasfile)

# this pipeline is for crappy feet at the moment
pipe = [
        lasfile,
        {
            'type': 'filters.hag_nn',
            'count': '2'
        },
        {
            'type': 'filters.range',
            'limits': 'HeightAboveGround[15:70]'
        },
        {
            'type': 'filters.range',
            'limits': 'NumberOfReturns[0:3]'
        },
        {
            'type': 'filters.range',
            'limits': f'Intensity[{I_min}:{I_max}]'
        },
        {
            'filename': rasfile,
            'gdaldriver': 'GTiff',
            'output_type': 'count',
            'resolution': 0.5,
            'radius': 2,
            'type': 'writers.gdal', 
            'where': '(Classification == 7)'
        },
        {
            'type': 'writers.las',
            'filename': out_laz,
            'a_srs': srs,
            'extra_dims': 'HeightAboveGround=float'
        }
    ]


with open(jsonpath, 'w') as j:
    json.dump(pipe, j)

# make pdal command
cmd = f'pdal pipeline -i {jsonpath}'

# run pdal  pipeline
_ = subprocess.run(cmd, shell=True, capture_output=True)
if len(_.stderr) > 0:
    print(_.stderr)




# %%


# %%

# %%

# %%

# %%

# %%
pipe = pdal.Pipeline(json.dumps(pipe))
# %%

pipe.validate()
pipe.execute()
arr = pipe.arrays[0]
df = pd.DataFrame(arr)
df = dd.from_pandas(df, npartitions=4)
# %%

def geometrizer(row):
    g = Point(row.X, row.Y, row.X)
    return(g)

geometry = df.apply(geometrizer, axis=1, meta=('shapely.geometry.point.Point'))

# %%



# %%
