import * as Stream from 'stream'
import ImapCluster from './imapCluster'
import * as Compress from './compress'
import * as fs from 'fs'
import * as Async from 'async'

export default class mainWrite extends Stream.Writable {

	private packageBuffer ( buffer: Buffer, enpty: boolean ) {
		if ( !enpty ) {
			return Compress.packetBuffer ( 5, this.count ++, this.uuid, buffer )
		}

		Compress.encrypt ( buffer, this.password, ( err, data ) => {
			return Compress.packetBuffer ( 0, this.count ++, this.uuid, data )
		})
		
	}

	private src: Stream.Readable = null

	constructor ( private imapCluster: ImapCluster, private password: string, private isSsl: boolean, private uuid: string, private count: number ) {
		super ()
		
	}

	public _write ( chunk: Buffer, encoding, down ) {
		console.log (`[${this.uuid}] got data ${chunk.length}`)
		
		if ( chunk.length < 3000 || this.isSsl && this.count < 6 ) {
			
			this.imapCluster.pushMainData ( this.packageBuffer ( chunk, false ))
			return down ()
		}
		
		const data: ISaveDataPool = this.imapCluster.getDataUuid ( this.uuid ) ||
		{
			buffer: null,
			uuid: this.uuid,
			index: this.count ++,
			noExcrypt: this.isSsl
		}

		if ( data.buffer ) {
			console.log ('imapCluster.getDataUuid find data')
			data.buffer = Buffer.concat ([ data.buffer, chunk ])
		}
			
		else {
			data.buffer = chunk
		}
			

		this.imapCluster.pushData ( data )
		return down ()
		
	}

	public sendEnd () {
		
		const buffer = Compress.packetBuffer ( 2, this.count, this.uuid, null )
		this.imapCluster.pushMainData ( buffer )
	}
	
}