import pandas as pd
import geopandas as gpd
import glob as glob
import gzip as gzip

def treatSpecialCommuneId(x):
    """
    Function to treat special commune id cases
    """
    testing  = x[0:2]+x[3:6]
    if testing == '51411' or testing == '51651' :
        return '51612'
    elif testing == '51347':
       return '51030'   
    elif testing == '02669':
        return '02053'    
    else:
        return x[0:2]+x[3:6]

listCommunesJson=glob.glob('cadastre*.json.gz')
strident='052025'
# fusion des json
fTime=True
for row in listCommunesJson:
    with gzip.open(row) as f:
       dfComm=gpd.read_file(f)
       if fTime:
           dfTotal=dfComm
           fTime=False
       else:
           dfTotal=pd.concat([dfTotal,dfComm])
           
posttreatOldCommune=lambda x: x[0:2]+'0'+x[2:] if x[5:8] == '000' else x[0:2]+'0'+x[5:8]+'000'+x[8:]
posttreatNormalCommune=lambda x: x[0:2]+'0'+x[2:] 

dfTotal2=dfTotal.copy()

dfTotal['idTest']=dfTotal['id'].apply(posttreatOldCommune)
dfTotal.set_index('idTest',inplace=True)
dfTotal=dfTotal[['id', 'commune', 'prefixe', 'section', 'numero', 'contenance','created', 'updated', 'geometry']]
dfTotal.columns=['identifiant_cadastre', 'commune_id_cadastre', 'prefix_cadastre', 'section_cadastre', 'numero_cadastre', 'contenance_cadastre','date_created', 'date_updated', 'geom_4326']

dfTotal2['idTest']=dfTotal2['id'].apply(posttreatNormalCommune)
dfTotal2.set_index('idTest',inplace=True)
dfTotal2=dfTotal2[['id', 'commune', 'prefixe', 'section', 'numero', 'contenance','created', 'updated', 'geometry']]
dfTotal2.columns=['identifiant_cadastre', 'commune_id_cadastre', 'prefix_cadastre', 'section_cadastre', 'numero_cadastre', 'contenance_cadastre','date_created', 'date_updated', 'geom_4326']


explCivc=pd.read_excel('EXPLOITATIONS.xlsx')
explCivc.columns=['id','code','EVV','name','email','MMME','nomofficiel','nomofficiel2','adresse','adresse2','CP','ville']
explCivc=explCivc.astype({'code':'int'})
explCivc=explCivc.astype({'id':'int'})
explCivc.to_csv('./fusion_EXPL_'+strident+'.csv',sep=';',index=False, na_rep='NaN')

spcv=pd.read_excel('SPCV.xlsx')
spcv['id']= spcv['Identifiant         PCV'].str.replace(' ','0')

## filter only active parcels
spcv=spcv[spcv['Code état de gestion']==2]
spcv=spcv[['Identifiant         PCV', 'N° unique SPCV      dans la PCV',
       'ID Exploitation', 'Code                Cépage',
       'Code porte          greffe', 
       'Code bailleur       nature',
       'Code propriétaire   fermier ou          bailleur',
       'Année               de plantation', 'Superficie en ca', 'Ecart rang',
       'Ecart pied']]
spcv.columns=['identifiant_pcv_cvi', 'num_spcv',
       'exploit_id', 'cepage',
       'portegreffe', 
       'bailleur_nature_id',
       'owner_farmer_bailleur_id',
       'plant_year', 'superficie', 'ecart_rang',
       'ecart_pied']
resultSPCV = pd.merge(spcv, explCivc, how='left', left_on='exploit_id', right_on='id')

resultSPCV.to_csv('./fusion_SPCV_'+strident+'.csv',sep=';',index=False, na_rep='NaN')


pcv=pd.read_excel('PCV.xlsx',dtype={'Identifiant commune': str} )
pcv['id']= pcv['Identifiant         PCV'].str.replace(' ','0')

pcv.set_index('id',inplace=True)
pcv=pcv[['Identifiant         PCV','Identifiant commune',
       'Section             Cadastrale',
       'Préfixe             Référence           Cadastrale',
       'Numéro              Parcelle', 'Code                DSF',
       'Nom                 Propriétaire', 'code lieu-dit', 'Contenance']]
pcv.columns=['identifiant_cvi','commune_id_cvi','section_cvi','prefix_cvi',
       'numero_cvi', 'dsf_cvi',
       'owner_name', 'lieudit_id', 'contenance_cvi']  

pcv['commune_id_cvi_insee']=pcv['commune_id_cvi'].apply(lambda x: treatSpecialCommuneId(x))    
resultPCV = pd.merge(pcv, dfTotal, how='left', left_index=True, right_index=True)

## Vert Toulon
##  resultPCV[resultPCV['geom_4326'].isnull()][resultPCV['identifiant_cvi'].str.contains('510611575')]
##  dfTotal2[dfTotal2['identifiant_cadastre'].str.contains('51611575')]
##  dfTotal2[dfTotal2.index.str.contains('510611575')]

dfTemp=pd.merge(resultPCV[resultPCV['geom_4326'].isnull()][['identifiant_cvi', 'commune_id_cvi', 'section_cvi', 'prefix_cvi',
       'numero_cvi', 'dsf_cvi', 'owner_name', 'lieudit_id', 'contenance_cvi',
       'commune_id_cvi_insee']], dfTotal2, how='left', left_index=True, right_index=True)
dfTemp=dfTemp[dfTemp['geom_4326'].notnull()]

resultPCV.update(dfTemp)
resultPCV.to_csv('./fusion_PCV_'+strident+'.csv',sep=';',index=False, na_rep='NULL')


df1=spcv.drop_duplicates(['identifiant_pcv_cvi','exploit_id'])
df2=spcv.drop_duplicates(['identifiant_pcv_cvi','exploit_id']).drop_duplicates(['identifiant_pcv_cvi'])
diff=pd.concat([df1,df2]).drop_duplicates(keep=False)
df = df1.merge(df2, how = 'inner' ,indicator=False)
