import {fromJS, Map, Set} from 'immutable'
import {call, put, select} from 'redux-saga/effects';
import {Apis} from 'shared/api_client';

/**
    This loadFollows both 'blog' and 'ignore'
*/

//fetch for follow/following count
export function* fetchFollowCount(account) {
    const counts = yield call(Apis.follow, 'get_follow_count', account)
    yield put({type: 'global/UPDATE', payload: {
        key: ['follow_count', account],
        updater: m => m.mergeDeep({'follower_count': counts.follower_count,
        'following_count': counts.following_count})
    }})
}

// Test limit with 2 (not 1, infinate looping)
export function* loadFollows(method, account, type, force = false) {
    if(yield select(state => state.global.getIn(['follow', method, account, type + '_loading']))) {
        // console.log('Already loading', method, account, type)
        return
    }

    if(!force) {
        const hasResult = yield select(state => state.global.hasIn(['follow', method, account, type + '_result']))
        if(hasResult) {
            // console.log('Already loaded', method, account, type)
            return
        }
    }

    yield put({type: 'global/UPDATE', payload: {
        key: ['follow', method, account],
        notSet: Map(),
        updater: m => m.set(type + '_loading', true),
    }})

    yield loadFollowsLoop(method, account, type)
}

function* loadFollowsLoop(method, account, type, start = '', limit = 100) {
    method == "get_followers" ? limit = 1000 : limit;
    const res = fromJS(yield Apis.follow(method, account, start, type, limit));
    // console.log('res.toJS()', res.toJS())

    let cnt = 0
    let lastAccountName = null

    yield put({type: 'global/UPDATE', payload: {
        key: ['follow_inprogress', method, account],
        notSet: Map(),
        updater: m => {
            m = m.asMutable()
            res.forEach(value => {
                cnt++

                const whatList = value.get('what')
                const accountNameKey = method === "get_following" ? "following" : "follower";
                const accountName = lastAccountName = value.get(accountNameKey)
                whatList.forEach(what => {
                    //currently this is always true: what === type
                    m.update(what, Set(), s => s.add(accountName))
                })
            })
            return m.asImmutable()
        }
    }})

    if(cnt === limit) {
        // This is paging each block of up to limit results
        yield call(loadFollowsLoop, method, account, type, lastAccountName)
    } else {
        // This condition happens only once at the very end of the list.
        // Every account has a different followers and following list for: blog, ignore
        yield put({type: 'global/UPDATE', payload: {
            key: [],
            updater: m => {
                m = m.asMutable()

                const result = m.getIn(['follow_inprogress', method, account, type], Set())
                m.deleteIn(['follow_inprogress', method, account, type])
                m.updateIn(['follow', method, account], Map(), mm => mm.merge({
                    // Count may be set separately without loading the full xxx_result set
                    [type + '_count']: result.size,
                    [type + '_result']: result.sort().reverse(),
                    [type + '_loading']: false,
                }))
                return m.asImmutable()
            }
        }})
    }
}

@@ -344,32 +344,41 @@
 %0A    yield put(%7B
+%0A        
 type: 'global/UP
@@ -375,32 +375,40 @@
 'global/UPDATE',
+%0A       
  payload: %7B%0A    
@@ -395,32 +395,36 @@
      payload: %7B%0A
+    
         key: %5B'f
@@ -447,32 +447,36 @@
 count%5D,%0A        
+    
 updater: m =%3E m.
@@ -486,17 +486,33 @@
 geDeep(%7B
-'
+%0A                
 follower
@@ -513,25 +513,24 @@
 llower_count
-'
 : counts.fol
@@ -550,17 +550,24 @@
         
+    
-'
+    
 followin
@@ -573,17 +573,16 @@
 ng_count
-'
 : counts
@@ -1181,32 +1181,41 @@
 %0A    yield put(%7B
+%0A        
 type: 'global/UP
@@ -1212,32 +1212,40 @@
 'global/UPDATE',
+%0A       
  payload: %7B%0A    
@@ -1232,32 +1232,36 @@
      payload: %7B%0A
+    
         key: %5B'f
@@ -1286,32 +1286,36 @@
 count%5D,%0A        
+    
 notSet: Map(),%0A 
@@ -1305,32 +1305,36 @@
  notSet: Map(),%0A
+    
         updater:
@@ -1512,16 +1512,19 @@
 ) %7B%0A    
+if(
 method =
@@ -1524,16 +1524,17 @@
 ethod ==
+=
  %22get_fo
@@ -1541,18 +1541,17 @@
 llowers%22
- ?
+)
  limit =
@@ -1559,16 +1559,8 @@
 1000
- : limit
 ;%0A  
@@ -1865,33 +1865,35 @@
        updater: 
-m
+(m)
  =%3E %7B%0A          
@@ -1936,21 +1936,23 @@
 forEach(
+(
 value
+)
  =%3E %7B%0A  
@@ -1972,10 +1972,14 @@
  cnt
-++
+ += 1;
 %0A%0A  
@@ -2234,20 +2234,22 @@
 forEach(
+(
 what
+)
  =%3E %7B%0A  
@@ -2893,25 +2893,27 @@
    updater: 
-m
+(m)
  =%3E %7B%0A      

fix ternary op, eslint