package req

import (
	
	
	
	
	
	
	urlpkg 
	
	
	
	
)

type ParallelDownload struct {
	url          string
	client       *Client
	concurrency  int
	output       io.Writer
	filename     string
	segmentSize  int64
	perm         os.FileMode
	tempRootDir  string
	tempDir      string
	taskCh       chan *downloadTask
	doneCh       chan struct{}
	wgDoneCh     chan struct{}
	errCh        chan error
	wg           sync.WaitGroup
	taskMap      map[int]*downloadTask
	taskNotifyCh chan *downloadTask
	mu           sync.Mutex
	lastIndex    int
}

func ( *ParallelDownload) ( *downloadTask) {
	.mu.Lock()
	.taskMap[.index] = 
	.mu.Unlock()
	go func() {
		select {
		case .taskNotifyCh <- :
		case <-.doneCh:
		}
	}()
}

func ( *ParallelDownload) ( int) *downloadTask {
	.mu.Lock()
	if ,  := .taskMap[];  {
		delete(.taskMap, )
		.mu.Unlock()
		return 
	}
	.mu.Unlock()
	for {
		 := <-.taskNotifyCh
		if .index ==  {
			.mu.Lock()
			delete(.taskMap, )
			.mu.Unlock()
			return 
		}
	}
}

func md5Sum( string) string {
	 := md5.Sum([]byte())
	return hex.EncodeToString([:])
}

func ( *ParallelDownload) () error {
	if .concurrency <= 0 {
		.concurrency = 5
	}
	if .segmentSize <= 0 {
		.segmentSize = 1073741824 // 10MB
	}
	if .perm == 0 {
		.perm = 0777
	}
	if .tempRootDir == "" {
		.tempRootDir = os.TempDir()
	}
	.tempDir = filepath.Join(.tempRootDir, md5Sum(.url))
	if .client.DebugLog {
		.client.log.Debugf("use temporary directory %s", .tempDir)
		.client.log.Debugf("download with %d concurrency and %d bytes segment size", .concurrency, .segmentSize)
	}
	 := os.MkdirAll(.tempDir, os.ModePerm)
	if  != nil {
		return 
	}

	.taskCh = make(chan *downloadTask)
	.doneCh = make(chan struct{})
	.wgDoneCh = make(chan struct{})
	.errCh = make(chan error)
	.taskMap = make(map[int]*downloadTask)
	.taskNotifyCh = make(chan *downloadTask)
	return nil
}

func ( *ParallelDownload) ( int64) *ParallelDownload {
	.segmentSize = 
	return 
}

func ( *ParallelDownload) ( string) *ParallelDownload {
	.tempRootDir = 
	return 
}

func ( *ParallelDownload) ( os.FileMode) *ParallelDownload {
	.perm = 
	return 
}

func ( *ParallelDownload) ( int) *ParallelDownload {
	.concurrency = 
	return 
}

func ( *ParallelDownload) ( io.Writer) *ParallelDownload {
	if  != nil {
		.output = 
	}
	return 
}

func ( *ParallelDownload) ( string) *ParallelDownload {
	.filename = 
	return 
}

func getRangeTempFile(,  int64,  string) string {
	return filepath.Join(, fmt.Sprintf("temp-%d-%d", , ))
}

type downloadTask struct {
	index                int
	rangeStart, rangeEnd int64
	tempFilename         string
	tempFile             *os.File
}

func ( *ParallelDownload) ( *downloadTask,  ...context.Context) {
	.wg.Add(1)
	defer .wg.Done()
	.tempFilename = getRangeTempFile(.rangeStart, .rangeEnd, .tempDir)
	if .client.DebugLog {
		.client.log.Debugf("downloading segment %d-%d", .rangeStart, .rangeEnd)
	}
	,  := os.OpenFile(.tempFilename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if  != nil {
		.errCh <- 
		return
	}
	 = .client.Get(.url).
		SetHeader("Range", fmt.Sprintf("bytes=%d-%d", .rangeStart, .rangeEnd)).
		SetOutput().
		Do(...).Err

	if  != nil {
		.errCh <- 
		return
	}
	.tempFile = 
	.completeTask()
}

func ( *ParallelDownload) ( ...context.Context) {
	for {
		select {
		case  := <-.taskCh:
			.handleTask(, ...)
		case <-.doneCh:
			return
		}
	}
}

func ( *ParallelDownload) () {
	defer .wg.Done()
	,  := .getOutputFile()
	if  != nil {
		.errCh <- 
		return
	}
	for  := 0; ; ++ {
		 := .popTask()
		,  := os.Open(.tempFilename)
		if  != nil {
			.errCh <- 
			return
		}
		_,  = io.Copy(, )
		.Close()
		if  != nil {
			.errCh <- 
			return
		}
		if  < .lastIndex {
			continue
		}
		break
	}
	if .client.DebugLog {
		.client.log.Debugf("removing temporary directory %s", .tempDir)
	}
	 = os.RemoveAll(.tempDir)
	if  != nil {
		.errCh <- 
	}
}

func ( *ParallelDownload) ( ...context.Context) error {
	 := .ensure()
	if  != nil {
		return 
	}
	for  := 0;  < .concurrency; ++ {
		go .startWorker(...)
	}
	 := .client.Head(.url).Do(...)
	if .Err != nil {
		return .Err
	}
	if .ContentLength <= 0 {
		return fmt.Errorf("bad content length: %d", .ContentLength)
	}
	.lastIndex = int(math.Ceil(float64(.ContentLength)/float64(.segmentSize))) - 1
	.wg.Add(1)
	go .mergeFile()
	go func() {
		.wg.Wait()
		close(.wgDoneCh)
	}()
	 := .ContentLength
	 := int64(0)
	for  := 0; ; ++ {
		 :=  + (.segmentSize - 1)
		if  > ( - 1) {
			 =  - 1
		}
		 := &downloadTask{
			index:      ,
			rangeStart: ,
			rangeEnd:   ,
		}
		.taskCh <- 
		if  < ( - 1) {
			 =  + 1
			continue
		}
		break
	}
	select {
	case <-.wgDoneCh:
		if .client.DebugLog {
			if .filename != "" {
				.client.log.Debugf("download completed from %s to %s", .url, .filename)
			} else {
				.client.log.Debugf("download completed for %s", .url)
			}
		}
		close(.doneCh)
	case  := <-.errCh:
		return 
	}
	return nil
}

func ( *ParallelDownload) () (io.Writer, error) {
	 := .output
	if  != nil {
		return , nil
	}
	if .filename == "" {
		,  := urlpkg.Parse(.url)
		if  != nil {
			panic()
		}
		 := strings.Split(.Path, "/")
		for  := len() - 1;  > 0; -- {
			if [] != "" {
				.filename = []
				break
			}
		}
		if .filename == "" {
			.filename = "download"
		}
	}
	if .client.outputDirectory != "" && !filepath.IsAbs(.filename) {
		.filename = filepath.Join(.client.outputDirectory, .filename)
	}
	return os.OpenFile(.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, .perm)
}